summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.kt
blob: 4a8dfb7ebd9cf49391725287f4262e2378332a4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui

import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.ide.DataManager
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.PlatformEditorBundle
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameDecorator
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.FontComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.UIUtil
import java.awt.RenderingHints
import java.awt.Window
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.*

private val settings: UISettings
  get() = UISettings.getInstance()
private val generalSettings
  get() = GeneralSettings.getInstance()
private val lafManager
  get() = LafManager.getInstance()

private val cdShowToolWindowBars
  get() = CheckboxDescriptor(message("checkbox.show.tool.window.bars"), PropertyBinding({ !settings.hideToolStripes },
                                                                                        { settings.hideToolStripes = !it }),
                             groupName = windowOptionGroupName)
private val cdShowToolWindowNumbers
  get() = CheckboxDescriptor(message("checkbox.show.tool.window.numbers"), settings::showToolWindowsNumbers,
                             groupName = windowOptionGroupName)
private val cdEnableMenuMnemonics
  get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.menu.check.box"), PropertyBinding({ !settings.disableMnemonics },
                                                                                                        { settings.disableMnemonics = !it }),
                             groupName = windowOptionGroupName)
private val cdEnableControlsMnemonics
  get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.controls.check.box"),
                             PropertyBinding({ !settings.disableMnemonicsInControls }, { settings.disableMnemonicsInControls = !it }),
                             groupName = windowOptionGroupName)
private val cdSmoothScrolling
  get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), settings::smoothScrolling, groupName = uiOptionGroupName)
private val cdWidescreenToolWindowLayout
  get() = CheckboxDescriptor(message("checkbox.widescreen.tool.window.layout"), settings::wideScreenSupport,
                             groupName = windowOptionGroupName)
private val cdLeftToolWindowLayout
  get() = CheckboxDescriptor(message("checkbox.left.toolwindow.layout"), settings::leftHorizontalSplit, groupName = windowOptionGroupName)
private val cdRightToolWindowLayout
  get() = CheckboxDescriptor(message("checkbox.right.toolwindow.layout"), settings::rightHorizontalSplit, groupName = windowOptionGroupName)
private val cdUseCompactTreeIndents
  get() = CheckboxDescriptor(message("checkbox.compact.tree.indents"), settings::compactTreeIndents, groupName = uiOptionGroupName)
private val cdShowTreeIndents
  get() = CheckboxDescriptor(message("checkbox.show.tree.indent.guides"), settings::showTreeIndentGuides, groupName = uiOptionGroupName)
private val cdDnDWithAlt
  get() = CheckboxDescriptor(message("dnd.with.alt.pressed.only"), settings::dndWithPressedAltOnly, groupName = uiOptionGroupName)
private val cdSeparateMainMenu
  get() = CheckboxDescriptor(message("checkbox.main.menu.separate.toolbar"), settings::separateMainMenu, groupName = uiOptionGroupName)

private val cdUseTransparentMode
  get() = CheckboxDescriptor(message("checkbox.use.transparent.mode.for.floating.windows"), settings.state::enableAlphaMode)
private val cdOverrideLaFFont get() = CheckboxDescriptor(message("checkbox.override.default.laf.fonts"), settings::overrideLafFonts)
private val cdUseContrastToolbars
  get() = CheckboxDescriptor(message("checkbox.acessibility.contrast.scrollbars"), settings::useContrastScrollbars)
private val cdMergeMainMenuWithWindowTitle
  get() = CheckboxDescriptor(message("checkbox.merge.main.menu.with.window.title"), settings::mergeMainMenuWithWindowTitle, groupName = windowOptionGroupName)
private val cdFullPathsInTitleBar
  get() = CheckboxDescriptor(message("checkbox.full.paths.in.window.header"), settings::fullPathsInWindowHeader)
private val cdShowMenuIcons
  get() = CheckboxDescriptor(message("checkbox.show.icons.in.menu.items"), settings::showIconsInMenus, groupName = windowOptionGroupName)

internal fun getAppearanceOptionDescriptors(): Sequence<OptionDescription> {
  return sequenceOf(
    cdShowToolWindowBars,
    cdShowToolWindowNumbers,
    cdEnableMenuMnemonics,
    cdEnableControlsMnemonics,
    cdSmoothScrolling,
    cdWidescreenToolWindowLayout,
    cdLeftToolWindowLayout,
    cdRightToolWindowLayout,
    cdUseCompactTreeIndents,
    cdShowTreeIndents,
    cdDnDWithAlt,
    cdFullPathsInTitleBar,
    cdSeparateMainMenu
  ).map(CheckboxDescriptor::asUiOptionDescriptor)
}

internal class AppearanceConfigurable : BoundSearchableConfigurable(message("title.appearance"), "preferences.lookFeel") {
  private var shouldUpdateLaF = false

  private val propertyGraph = PropertyGraph()
  private val lafProperty = propertyGraph.graphProperty { lafManager.lookAndFeelReference }
  private val syncThemeProperty = propertyGraph.graphProperty { lafManager.autodetect }

  override fun createPanel(): DialogPanel {
    lafProperty.afterChange({ QuickChangeLookAndFeel.switchLafAndUpdateUI(lafManager, lafManager.findLaf(it), true) }, disposable!!)
    syncThemeProperty.afterChange({ lafManager.autodetect = it }, disposable!!)

    return panel {
      row(message("combobox.look.and.feel")) {
        val theme = comboBox(lafManager.lafComboBoxModel, lafManager.lookAndFeelCellRenderer)
          .bindItem(lafProperty)
          .accessibleName(message("combobox.look.and.feel"))

        val syncCheckBox = checkBox(message("preferred.theme.autodetect.selector"))
          .bindSelected(syncThemeProperty)
          .visible(lafManager.autodetectSupported)
          .gap(RightGap.SMALL)

        theme.enabledIf(syncCheckBox.selected.not())
        cell(lafManager.settingsToolbar)
          .visibleIf(syncCheckBox.selected)
      }.layout(RowLayout.INDEPENDENT)

      row {
        link(message("link.get.more.themes")) {
          val settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(it.source as ActionLink))
          settings?.select(settings.find("preferences.pluginManager"), "/tag:theme")
        }
      }

      row {
        val overrideLaF = checkBox(cdOverrideLaFFont)
          .shouldUpdateLaF()
          .gap(RightGap.SMALL)
        cell(FontComboBox())
          .bind(
            { it.fontName },
            { it, value -> it.fontName = value },
            MutableProperty({ if (settings.overrideLafFonts) settings.fontFace else JBFont.label().family },
                            { settings.fontFace = it })
          )
          .shouldUpdateLaF()
          .enabledIf(overrideLaF.selected)
          .accessibleName(cdOverrideLaFFont.name)

        fontSizeComboBox({ if (settings.overrideLafFonts) settings.fontSize else JBFont.label().size },
                         { settings.fontSize = it },
                         settings.fontSize)
          .label(message("label.font.size"))
          .shouldUpdateLaF()
          .enabledIf(overrideLaF.selected)
          .accessibleName(message("label.font.size"))
      }.topGap(TopGap.SMALL)

      group(message("title.accessibility")) {
        row {
          val isOverridden = GeneralSettings.isSupportScreenReadersOverridden()
          val mask = if (SystemInfo.isMac) InputEvent.META_MASK else InputEvent.CTRL_MASK
          val ctrlTab = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, mask))
          val ctrlShiftTab = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, mask + InputEvent.SHIFT_MASK))
          checkBox(message("checkbox.support.screen.readers"))
            .bindSelected(generalSettings::isSupportScreenReaders, generalSettings::setSupportScreenReaders)
            .comment(message("support.screen.readers.tab", ctrlTab, ctrlShiftTab))
            .enabled(!isOverridden)

          comment(if (isOverridden) message("overridden.by.jvm.property", GeneralSettings.SUPPORT_SCREEN_READERS)
                  else message("support.screen.readers.comment"))
        }

        row {
          checkBox(cdUseContrastToolbars)
        }

        val supportedValues = ColorBlindness.values().filter { ColorBlindnessSupport.get(it) != null }
        if (supportedValues.isNotEmpty()) {
          val colorBlindnessProperty = MutableProperty({ settings.colorBlindness }, { settings.colorBlindness = it })
          val onApply = {
            // callback executed not when all changes are applied, but one component by one, so, reload later when everything were applied
            ApplicationManager.getApplication().invokeLater(Runnable {
              DefaultColorSchemesManager.getInstance().reload()
              (EditorColorsManager.getInstance() as EditorColorsManagerImpl).schemeChangedOrSwitched(null)
            })
          }

          row {
            if (supportedValues.size == 1) {
              checkBox(UIBundle.message("color.blindness.checkbox.text"))
                .comment(UIBundle.message("color.blindness.checkbox.comment"))
                .bind({ if (it.isSelected) supportedValues.first() else null },
                      { it, value -> it.isSelected = value != null },
                      colorBlindnessProperty)
                .onApply(onApply)
            }
            else {
              val enableColorBlindness = checkBox(UIBundle.message("color.blindness.combobox.text"))
                .applyToComponent { isSelected = colorBlindnessProperty.get() != null }
              comboBox(supportedValues)
                .enabledIf(enableColorBlindness.selected)
                .applyToComponent { renderer = SimpleListCellRenderer.create("") { PlatformEditorBundle.message(it.key) } }
                .comment(UIBundle.message("color.blindness.combobox.comment"))
                .bind({ if (enableColorBlindness.component.isSelected) it.selectedItem as? ColorBlindness else null },
                      { it, value -> it.selectedItem = value ?: supportedValues.first() },
                      colorBlindnessProperty)
                .onApply(onApply)
                .accessibleName(UIBundle.message("color.blindness.checkbox.text"))
            }

            link(UIBundle.message("color.blindness.link.to.help")
            ) { HelpManager.getInstance().invokeHelp("Colorblind_Settings") }
          }
        }
      }

      group(message("group.ui.options")) {
        val leftColumnControls = sequence<Row.() -> Unit> {
          yield({ checkBox(cdShowTreeIndents) })
          yield({ checkBox(cdUseCompactTreeIndents) })
          yield({ checkBox(cdEnableMenuMnemonics) })
          yield({ checkBox(cdEnableControlsMnemonics) })
          if (SystemInfo.isWindows && ExperimentalUI.isNewToolbar()) {
            yield({ checkBox(cdSeparateMainMenu) })
          }
        }
        val rightColumnControls = sequence<Row.() -> Unit> {
          yield({
                  checkBox(cdSmoothScrolling)
                    .gap(RightGap.SMALL)
                  contextHelp(message("checkbox.smooth.scrolling.description"))
                })
          yield({ checkBox(cdDnDWithAlt) })
          if (IdeFrameDecorator.isCustomDecorationAvailable()) {
            yield({
                    val overridden = UISettings.isMergeMainMenuWithWindowTitleOverridden
                    checkBox(cdMergeMainMenuWithWindowTitle)
                      .enabled(!overridden)
                      .gap(RightGap.SMALL)
                    if (overridden) {
                      contextHelp(message("option.is.overridden.by.jvm.property", UISettings.MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY))
                    }
                    comment(message("checkbox.merge.main.menu.with.window.title.comment"))
                  })
          }
          yield({ checkBox(cdFullPathsInTitleBar) })
          yield({ checkBox(cdShowMenuIcons) })
        }

        // Since some of the columns have variable number of items, enumerate them in a loop, while moving orphaned items from the right
        // column to the left one:
        val leftIt = leftColumnControls.iterator()
        val rightIt = rightColumnControls.iterator()
        while (leftIt.hasNext() || rightIt.hasNext()) {
          when {
            leftIt.hasNext() && rightIt.hasNext() -> twoColumnsRow(leftIt.next(), rightIt.next())
            leftIt.hasNext() -> twoColumnsRow(leftIt.next())
            rightIt.hasNext() -> twoColumnsRow(rightIt.next()) // move from right to left
          }
        }

        val backgroundImageAction = ActionManager.getInstance().getAction("Images.SetBackgroundImage")
        if (backgroundImageAction != null) {
          row {
            button(message("background.image.button"), backgroundImageAction)
              .enabled(ProjectManager.getInstance().openProjects.isNotEmpty())
          }
        }
      }

      if (Registry.`is`("ide.transparency.mode.for.windows") &&
          WindowManagerEx.getInstanceEx().isAlphaModeSupported) {
        val settingsState = settings.state
        group(message("group.transparency")) {
          lateinit var checkbox: Cell<JBCheckBox>
          row {
            checkbox = checkBox(cdUseTransparentMode)
          }
          row(message("label.transparency.delay.ms")) {
            intTextField()
              .bindIntText(settingsState::alphaModeDelay)
              .columns(4)
          }.enabledIf(checkbox.selected)
          row(message("label.transparency.ratio")) {
            slider(0, 100, 10, 50)
              .labelTable(mapOf(
                0 to JLabel("0%"),
                50 to JLabel("50%"),
                100 to JLabel("100%")))
              .bindValue({ (settingsState.alphaModeRatio * 100f).toInt() }, { settingsState.alphaModeRatio = it / 100f })
              .showValueHint()
          }.enabledIf(checkbox.selected)
            .layout(RowLayout.INDEPENDENT)
        }
      }

      groupRowsRange(message("group.antialiasing.mode")) {
        twoColumnsRow(
          {
            val ideAAOptions =
              if (!AntialiasingType.canUseSubpixelAAForIDE())
                arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
              else
                AntialiasingType.values()
            comboBox(DefaultComboBoxModel(ideAAOptions), renderer = AAListCellRenderer(false))
              .label(message("label.text.antialiasing.scope.ide"))
              .bindItem(settings::ideAAType.toNullableProperty())
              .shouldUpdateLaF()
              .accessibleName(message("label.text.antialiasing.scope.ide"))
              .onApply {
                for (w in Window.getWindows()) {
                  for (c in UIUtil.uiTraverser(w).filter(JComponent::class.java)) {
                    GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent())
                  }
                }
              }
          },
          {
            val editorAAOptions =
              if (!AntialiasingType.canUseSubpixelAAForEditor())
                arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
              else
                AntialiasingType.values()
            comboBox(DefaultComboBoxModel(editorAAOptions), renderer = AAListCellRenderer(true))
              .label(message("label.text.antialiasing.scope.editor"))
              .bindItem(settings::editorAAType.toNullableProperty())
              .shouldUpdateLaF()
              .accessibleName(message("label.text.antialiasing.scope.editor"))
          }
        )
      }

      groupRowsRange(message("group.window.options")) {
        twoColumnsRow(
          { checkBox(cdShowToolWindowBars) },
          { checkBox(cdShowToolWindowNumbers) }
        )
        twoColumnsRow(
          { checkBox(cdLeftToolWindowLayout) },
          { checkBox(cdRightToolWindowLayout) }
        )
        twoColumnsRow(
          {
            checkBox(cdWidescreenToolWindowLayout)
              .gap(RightGap.SMALL)
            contextHelp(message("checkbox.widescreen.tool.window.layout.description"))
          })
      }

      group(message("group.presentation.mode")) {
        row(message("presentation.mode.fon.size")) {
          fontSizeComboBox({ settings.presentationModeFontSize },
                           { settings.presentationModeFontSize = it },
                           settings.presentationModeFontSize)
            .shouldUpdateLaF()
        }
      }
    }
  }

  override fun apply() {
    val uiSettingsChanged = isModified
    shouldUpdateLaF = false

    super.apply()

    if (shouldUpdateLaF) {
      LafManager.getInstance().updateUI()
    }
    if (uiSettingsChanged) {
      UISettings.getInstance().fireUISettingsChanged()
      EditorFactory.getInstance().refreshAllEditors()
    }
  }

  private fun <T : JComponent> Cell<T>.shouldUpdateLaF(): Cell<T> = onApply { shouldUpdateLaF = true }
}

private fun Row.fontSizeComboBox(getter: () -> Int, setter: (Int) -> Unit, defaultValue: Int): Cell<ComboBox<String>> {
  return fontSizeComboBox(MutableProperty({ getter().toString() }, { setter(getIntValue(it, defaultValue)) }))
}

private fun Row.fontSizeComboBox(prop: MutableProperty<String?>): Cell<ComboBox<String>> {
  val model = DefaultComboBoxModel(UIUtil.getStandardFontSizes())
  return comboBox(model)
    .accessibleName(message("presentation.mode.fon.size"))
    .applyToComponent {
      isEditable = true
      renderer = SimpleListCellRenderer.create("") { it.toString() }
      selectedItem = prop.get()
    }
    .bind(
      { component -> component.editor.item as String? },
      { component, value -> component.setSelectedItem(value) },
      prop
    )
}

private fun getIntValue(text: String?, defaultValue: Int): Int {
  if (text != null && text.isNotBlank()) {
    val value = text.toIntOrNull()
    if (value != null && value > 0) return value
  }
  return defaultValue
}

private fun getFloatValue(text: String?, defaultValue: Float): Float {
  if (text != null && text.isNotBlank()) {
    val value = text.toFloatOrNull()
    if (value != null && value > 0) return value
  }
  return defaultValue
}

private class AAListCellRenderer(private val myUseEditorFont: Boolean) : SimpleListCellRenderer<AntialiasingType>() {
  private val SUBPIXEL_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
  private val GREYSCALE_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON)

  override fun customize(list: JList<out AntialiasingType>, value: AntialiasingType, index: Int, selected: Boolean, hasFocus: Boolean) {
    val aaType = when (value) {
      AntialiasingType.SUBPIXEL -> SUBPIXEL_HINT
      AntialiasingType.GREYSCALE -> GREYSCALE_HINT
      AntialiasingType.OFF -> null
    }
    GraphicsUtil.setAntialiasingType(this, aaType)

    if (myUseEditorFont) {
      val scheme = EditorColorsManager.getInstance().globalScheme
      font = UIUtil.getFontWithFallback(scheme.getFont(EditorFontType.PLAIN))
    }

    text = value.presentableName
  }
}