61
67
@see: ed_style.StyleMgr
63
69
def __init__(self, parent, id_=wx.ID_ANY, title=_("Style Editor"),
64
style=wx.DEFAULT_DIALOG_STYLE | wx.RAISED_BORDER):
65
"""Initializes the Dialog
66
@todo: rework the layout
69
wx.Dialog.__init__(self, parent, id_, title, style=style)
70
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER):
71
super(StyleEditor, self).__init__(parent, id_, title, style=style)
72
74
self.LOG = wx.GetApp().GetLog()
73
self.preview = ed_basestc.EditraBaseStc(self, wx.ID_ANY, size=(-1, 200),
74
style=wx.SUNKEN_BORDER)
75
self.styles_orig = self.preview.GetStyleSet()
76
self.preview.SetCaretLineVisible(True)
77
self.styles_new = DuplicateStyleDict(self.styles_orig)
78
self.preview.SetStyles('preview', self.styles_new, True)
79
self.OpenPreviewFile('cpp')
80
# XXX On Windows the settings pane must be made before the
81
# sizer it is to be put in or it becomes unable to recieve
82
# focus. But is the exact opposite on mac/gtk. This is really
83
# a pain or possibly a bug?
84
if wx.Platform == '__WXMSW__':
85
self._settings = SettingsPanel(self)
75
self._panel = StyleEditorBox(self) #TODO
88
78
sizer = wx.BoxSizer(wx.VERTICAL)
91
self.ctrl_pane = wx.Panel(self, wx.ID_ANY)
92
ctrl_sizer = wx.BoxSizer(wx.HORIZONTAL) # Main Control Sizer
93
left_colum = wx.BoxSizer(wx.VERTICAL) # Left Column
94
right_colum = wx.BoxSizer(wx.VERTICAL) # Right Column
96
# XXX On Mac/GTK if panel is created before sizer all controls in
97
# it become unable to recieve focus from clicks, but it is the
98
# exact opposite on windows!
99
if wx.Platform != '__WXMSW__':
100
self._settings = SettingsPanel(self)
102
# Control Panel Left Column
103
left_colum.AddMany([((10, 10), 0),
104
(self.__StyleSheets(), 0, wx.ALIGN_LEFT),
106
(self.__LexerChoice(), 0, wx.ALIGN_LEFT),
108
(self.__StyleTags(), 1, wx.ALIGN_LEFT|wx.EXPAND),
110
ctrl_sizer.Add(left_colum, 0, wx.ALIGN_LEFT)
113
ctrl_sizer.Add(wx.StaticLine(self.ctrl_pane, size=(-1, 2),
114
style=wx.LI_VERTICAL),
115
0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND)
116
ctrl_sizer.Add((5, 5), 0)
118
# Control Panel Right Column
119
right_colum.Add(self._settings, 1, wx.ALIGN_LEFT | wx.EXPAND)
120
ctrl_sizer.AddMany([(right_colum, 1, wx.ALIGN_RIGHT | wx.EXPAND),
123
# Finish Control Panel Setup
124
self.ctrl_pane.SetSizer(ctrl_sizer)
125
sizer.AddMany([((10, 10)), (self.ctrl_pane, 0, wx.ALIGN_CENTER)])
128
pre_sizer = wx.BoxSizer(wx.HORIZONTAL)
129
pre_sizer.AddMany([((10, 10), 0),
130
(wx.StaticText(self, label=_("Preview") + u": "),
132
sizer.AddMany([((10, 10), 0), (pre_sizer, 0, wx.ALIGN_LEFT),
133
(self.preview, 0, wx.EXPAND | wx.BOTTOM)])
79
sizer.Add(self._panel, 1, wx.EXPAND)
136
82
b_sizer = wx.BoxSizer(wx.HORIZONTAL)
139
85
b_sizer.AddMany([(wx.Button(self, wx.ID_CANCEL, _("Cancel")), 0),
141
(wx.Button(self, wx.ID_SAVE, _("Export")), 0),
87
(wx.Button(self, wx.ID_SAVE, _("Save")), 0),
142
88
((5, 5), 0), (ok_b, 0)])
143
89
sizer.Add(b_sizer, 0, wx.ALIGN_RIGHT |
144
90
wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
146
92
# Finish the Layout
147
93
self.SetSizer(sizer)
148
self.SetAutoLayout(True)
150
self.EnableSettings(False)
153
97
self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL)
154
98
self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
155
self.Bind(wx.EVT_BUTTON, self.OnExport, id=wx.ID_SAVE)
156
self.Bind(wx.EVT_CHOICE, self.OnChoice)
157
self.Bind(wx.EVT_CHECKBOX, self.OnCheck)
99
self.Bind(wx.EVT_BUTTON, self.OnSave, id=wx.ID_SAVE)
158
100
self.Bind(wx.EVT_CLOSE, self.OnClose)
104
def ExportStyleSheet(self):
105
"""Writes the style sheet data out to a style sheet
109
saved = self._panel.SaveStyleSheet()
112
def OnCancel(self, evt):
113
"""Catches the cancel button clicks and checks if anything
114
needs to be done before closing the window.
115
@param evt: event that called this handler
118
self.LOG('[style_editor][evt] Cancel Clicked Closing Window')
121
def OnClose(self, evt):
122
"""Handles the window closer event
123
@param evt: event that called this handler
126
self.LOG("[style_editor][evt] Dialog closing...")
130
"""Catches the OK button click and checks if any changes need to be
131
saved before the window closes.
132
@param evt: event that called this handler
135
self.LOG('[style_editor][evt] Ok Clicked Closing Window')
136
modtype = self._panel.CheckForModifications()
139
if modtype == MOD_CHANGE_PRESENT:
140
msg = _("Some styles have been changed would "
141
"you like to save before exiting?")
142
elif modtype == MOD_DOESNT_EXIST:
143
msg = _("The new style sheet '%s' has not been saved "
144
"would you like to save before exiting?") % self._panel.StyleTheme
146
dlg = wx.MessageDialog(self, msg, _("Save Styles"),
147
style=wx.YES_NO | wx.YES_DEFAULT | \
148
wx.CANCEL | wx.ICON_INFORMATION)
150
result = dlg.ShowModal()
153
if result == wx.ID_NO:
154
# Get Current Selection to update buffers
155
sheet = self._panel.StyleTheme
156
path = self._panel.GetStyleSheetPath(sheet)
157
if os.path.exists(path):
158
UpdateBufferStyles(sheet)
160
elif result == wx.ID_CANCEL:
161
self.LOG('[style_editor][info] canceled closing')
163
result = self.ExportStyleSheet()
164
if result != wx.ID_CANCEL:
167
def OnSave(self, evt):
168
"""Catches save button event
169
@param evt: event that called this handler
172
self.LOG('[style_editor][evt] Export Clicked')
173
self.ExportStyleSheet()
175
#-----------------------------------------------------------------------------#
177
class StyleEditorBox(eclib.ControlBox):
178
"""StyleEditor main Panel"""
179
def __init__(self, parent):
180
super(StyleEditorBox, self).__init__(parent)
183
self._prevTheme = None
184
ctrlbar = self.CreateControlBar(wx.TOP)
185
ss_lst = util.GetResourceFiles(u'styles', get_all=True)
186
ss_lst = [sheet for sheet in ss_lst if not sheet.startswith('.')]
187
self._style_ch = wx.Choice(ctrlbar, ed_glob.ID_PREF_SYNTHEME,
188
choices=sorted(ss_lst))
189
bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD), wx.ART_MENU)
192
self._addbtn = eclib.PlateButton(ctrlbar, label=_("New"),
193
bmp=bmp, style=eclib.PB_STYLE_NOBG)
194
bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_REMOVE), wx.ART_MENU)
197
self._delbtn = eclib.PlateButton(ctrlbar, label=_("Remove"),
198
bmp=bmp, style=eclib.PB_STYLE_NOBG)
201
ss_lbl = wx.StaticText(ctrlbar, label=_("Style Theme") + u": ")
202
ctrlbar.AddControl(ss_lbl, wx.ALIGN_LEFT)
203
self.StyleTheme = Profile_Get('SYNTHEME', 'str')
204
ctrlbar.AddControl(self._style_ch, wx.ALIGN_LEFT)
205
ctrlbar.AddControl(self._addbtn, wx.ALIGN_LEFT)
206
self._addbtn.SetToolTipString(_("Create a new style theme"))
207
ctrlbar.AddControl(self._delbtn, wx.ALIGN_LEFT)
208
self._delbtn.SetToolTipString(_("Remove Style"))
209
self.SetWindow(StyleEditorPanel(self))
212
self.Bind(wx.EVT_CHOICE, self.OnThemeChoice, self._style_ch)
213
self.Bind(wx.EVT_BUTTON, self.OnButton)
214
self.Bind(wx.EVT_UPDATE_UI,
215
lambda evt: evt.Enable(not self.IsSystemStyleSheet()),
218
#--- Properties ----#
219
def __setStyleTheme(self, theme):
220
self._prevTheme = theme # Tracking for choice change
221
self._style_ch.SetStringSelection(theme)
222
StyleTheme = property(lambda self: self._style_ch.GetStringSelection(),
223
lambda self, val: self.__setStyleTheme(val))
224
SyntaxSheets = property(lambda self: self._style_ch.GetItems(),
225
lambda self, val: self._style_ch.SetItems(sorted(val)))
227
#---- Public Api ----#
228
def CheckForModifications(self, sheet_name=None):
229
"""Check for any unsaved modifications to the styling information
230
@return: modification type
233
if sheet_name is None:
234
sheet_name = self.StyleTheme # currently selected
236
if self.Window.DiffStyles():
237
modtype = MOD_CHANGE_PRESENT
238
elif not self.SheetExistOnDisk(sheet_name):
239
modtype = MOD_DOESNT_EXIST
242
def DoChangeStyleSheet(self, sheet_name):
243
"""Change the StyleEditor for the given style sheet"""
244
if not self.SheetExistOnDisk(sheet_name):
245
# Changing to a fully transient style sheet that has
246
# not yet been written to disk.
247
self.SetDisplayForTransientSheet(sheet_name)
249
self.Window.ChangeStyleSheet(sheet_name)
250
self.StyleTheme = sheet_name
252
def GetStyleSheetPath(self, sheet, syspath=False):
253
"""Get the on disk path to where the style sheet should
255
@param sheet: sheet name
258
cfgdir = ed_glob.CONFIG['STYLES_DIR']
260
cfgdir = ed_glob.CONFIG['SYS_STYLES_DIR']
261
sheet_path = os.path.join(cfgdir, sheet)
262
if not sheet_path.endswith(u"ess"):
263
sheet_path += u".ess"
266
def IsSystemStyleSheet(self):
267
"""Is the given style sheet a system provided one
271
# If it exists in user space it is not a system one
272
path = self.GetStyleSheetPath(self.StyleTheme)
273
return not os.path.exists(path)
275
def RefreshStyleSheets(self):
276
"""Update the list of style sheets"""
277
ss_lst = util.GetResourceFiles(u'styles', get_all=True)
278
ss_lst = [sname for sname in ss_lst if not sname.startswith('.')]
279
self.SyntaxSheets = ss_lst
281
def SaveStyleSheet(self, sheetname=None):
282
"""Save the changes to the currently selected StyleSheet
286
# Ensure user styles directory exists to save style sheet to
287
if ed_glob.CONFIG['STYLES_DIR'] == ed_glob.CONFIG['SYS_STYLES_DIR']:
288
path = util.GetUserConfigBase()
289
user_config = os.path.join(path, 'styles')
290
if not os.path.exists(user_config):
292
os.mkdir(user_config)
293
except (OSError, IOError), msg:
294
util.Log("[style_editor][err] %s" % msg)
296
ed_glob.CONFIG['STYLES_DIR'] = user_config
299
if sheetname is None:
300
sheetname = self.StyleTheme
301
sheet_path = self.GetStyleSheetPath(sheetname)
302
if self.WriteStyleSheet(sheet_path):
303
# Update Style Sheet Control
304
self.RefreshStyleSheets()
305
sheet = u".".join(os.path.basename(sheet_path).split(u'.')[:-1])
306
self.StyleTheme = sheet
307
self.Window.ResetTransientStyleData()
308
util.Log("[style_editor][info] Successfully exported: %s" % sheet)
310
if sheet_path.startswith(ed_glob.CONFIG['STYLES_DIR']) or \
311
sheet_path.startswith(ed_glob.CONFIG['SYS_STYLES_DIR']):
312
# Update editor windows/buffer to use new style sheet
313
UpdateBufferStyles(sheet)
317
def SetDisplayForTransientSheet(self, sheet_name):
318
"""Setup the display and editor data for a transient style sheet"""
319
self.Window.SetBlankStyle()
320
themes = self.SyntaxSheets
321
if sheet_name not in themes:
322
themes.append(sheet_name)
323
self.SyntaxSheets = themes
324
self.StyleTheme = sheet_name
326
def SheetExistOnDisk(self, sheet_name):
327
"""Check if the given style sheet exists on disk
328
@param sheet_name: style sheet name
332
path = self.GetStyleSheetPath(sheet_name) # User path
333
syspath = self.GetStyleSheetPath(sheet_name, True) # System path
334
exists = os.path.exists(path) or os.path.exists(syspath)
337
def WriteStyleSheet(self, path):
338
"""Write the current style data to the given path
345
writer = util.GetFileWriter(path)
346
writer.write(self.Window.GenerateStyleSheet())
348
except (AttributeError, IOError), msg:
349
util.Log('[style_editor][err] Failed to export style sheet')
350
util.Log('[style_editor][err] %s' % msg)
354
#---- Event Handlers ----#
356
def OnButton(self, evt):
357
"""Handle the Add/Remove Buttons"""
358
e_obj = evt.GetEventObject()
359
if e_obj is self._addbtn:
360
# TODO: warn about unsaved changes
361
fname = wx.GetTextFromUser(_("Enter style sheet name"),
362
_("New Style Sheet"),
365
# Case insensitive check
366
if fname.lower() in [name.lower() for name in self.SyntaxSheets]:
368
wx.MessageBox(_("The style %s already exists. Please choose a different name.") % fname,
369
style=wx.OK|wx.CENTER|wx.ICON_INFORMATION)
372
self.SetDisplayForTransientSheet(fname)
373
elif e_obj is self._delbtn:
374
path = self.GetStyleSheetPath(self.StyleTheme)
378
wx.MessageBox(_("Failed to delete style sheet:\nError:\n%s") % msg,
379
style=wx.OK|wx.CENTER|wx.ICON_ERROR)
381
self.RefreshStyleSheets()
382
self.StyleTheme = u"Default" # select the default style
383
self.DoChangeStyleSheet(self.StyleTheme)
387
def OnThemeChoice(self, evt):
388
"""Check if current style sheet has been saved when switching sheets"""
389
oldTheme = self._prevTheme
390
newTheme = self.StyleTheme # newly selected theme
392
modtype = self.CheckForModifications(self._prevTheme)
393
if modtype == MOD_CHANGE_PRESENT:
394
# prompt to save before changing
395
msg = _("Would you like to save the changes to '%s' before changing themes?\n\n"
396
"Selecting No will result in all changes being lost.")
398
elif modtype == MOD_DOESNT_EXIST:
399
# prompt to save unsaved sheet
400
msg = _("The new style theme '%s' has not been saved.\n\n"
401
"Would you like to save it before changing themes?")
405
dlg = wx.MessageDialog(self, msg, _("Save Styles"),
406
style=wx.YES_NO | wx.YES_DEFAULT | \
409
result = dlg.ShowModal()
412
# Save the style sheet
413
self.SaveStyleSheet(oldTheme)
415
# Change the style sheet to the newly selected one
416
self.DoChangeStyleSheet(newTheme)
418
#-----------------------------------------------------------------------------#
420
class StyleEditorPanel(wx.Panel):
421
"""Main panel for the editor portion of the StyleEditor"""
422
def __init__(self, parent):
423
super(StyleEditorPanel, self).__init__(parent)
426
self._settings = SettingsPanel(self)
427
self.preview = PreviewPanel(self)
428
self.prebuff = self.preview.GetPreviewBuffer() # TEMP HACK
429
self.styles_orig = DuplicateStyleDict(self.prebuff.GetStyleSet())
430
self.styles_new = DuplicateStyleDict(self.styles_orig)
431
self.prebuff.SetStyles('preview', self.styles_new, True)
432
self.preview.OpenPreviewFile('cpp')
435
self.StyleTags = self.styles_orig.keys()
437
self.EnableSettings(False)
159
440
self.Bind(wx.EVT_LISTBOX, self.OnListBox)
441
self.Bind(wx.EVT_CHOICE, self.OnChoice)
442
self.Bind(wx.EVT_CHECKBOX, self.OnCheck)
160
443
self.Bind(eclib.EVT_COLORSETTER, self.OnColor)
161
self.preview.Bind(wx.EVT_LEFT_UP, self.OnTextRegion)
162
self.preview.Bind(wx.EVT_KEY_UP, self.OnTextRegion)
165
def __LexerChoice(self):
166
"""Returns a sizer object containing a choice control with all
167
available lexers listed in it.
168
@return: sizer item containing a choice control with all available
169
syntax test files available
172
lex_sizer = wx.BoxSizer(wx.HORIZONTAL)
173
lexer_lbl = wx.StaticText(self.ctrl_pane, wx.ID_ANY,
174
_("Syntax Files") + u": ")
175
lexer_lst = wx.Choice(self.ctrl_pane, ed_glob.ID_LEXER,
176
choices=syntax.GetLexerList())
177
lexer_lst.SetToolTip(wx.ToolTip(_("Set the preview file type")))
178
lexer_lst.SetStringSelection(u"CPP")
179
lex_sizer.AddMany([((10, 10)), (lexer_lbl, 0, wx.ALIGN_CENTER_VERTICAL),
180
((5, 0)), (lexer_lst, 1, wx.ALIGN_CENTER_VERTICAL),
184
def __StyleSheets(self):
185
"""Returns a sizer item that contains a choice control with
186
all the available style sheets listed in it.
187
@return: sizer item holding all installed style sheets
190
ss_sizer = wx.BoxSizer(wx.HORIZONTAL)
191
ss_lbl = wx.StaticText(self.ctrl_pane, wx.ID_ANY,
192
_("Style Theme") + u": ")
193
ss_lst = util.GetResourceFiles(u'styles', get_all=True)
194
ss_choice = wx.Choice(self.ctrl_pane, ed_glob.ID_PREF_SYNTHEME,
195
choices=sorted(ss_lst))
196
ss_choice.SetToolTip(wx.ToolTip(_("Base new theme on existing one")))
197
ss_choice.SetStringSelection(Profile_Get('SYNTHEME', 'str'))
198
ss_new = wx.CheckBox(self.ctrl_pane, wx.ID_NEW, _("New"))
199
ss_new.SetToolTip(wx.ToolTip(_("Start a blank new style")))
200
ss_sizer.AddMany([((10, 10)), (ss_lbl, 0, wx.ALIGN_CENTER_VERTICAL),
202
(ss_choice, 0, wx.ALIGN_CENTER_VERTICAL), ((10, 0)),
203
(ss_new, 0, wx.ALIGN_CENTER_VERTICAL), ((10, 10))])
206
def __StyleTags(self):
207
"""Returns a sizer object containing a choice control with all
208
current style tags in it.
209
@return: sizer item containing list of all available style tags
212
style_sizer = wx.BoxSizer(wx.HORIZONTAL)
213
style_sizer2 = wx.BoxSizer(wx.VERTICAL)
215
style_lbl = wx.StaticText(self.ctrl_pane, wx.ID_ANY,
216
_("Style Tags") + u": ")
218
style_tags = self.styles_orig.keys()
220
if wx.Platform == '__WXMAC__':
223
style_lst = wx.ListBox(self.ctrl_pane, ID_STYLES, size=lsize,
224
choices=sorted(style_tags), style=wx.LB_SINGLE)
225
style_sizer2.AddMany([(style_lbl, 0, wx.ALIGN_CENTER_VERTICAL),
226
(style_lst, 1, wx.EXPAND)])
227
style_sizer.AddMany([((10, 10), 0),
229
wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND),
444
self.prebuff.Bind(wx.EVT_LEFT_UP, self.OnTextRegion)
445
self.prebuff.Bind(wx.EVT_KEY_UP, self.OnTextRegion)
447
def __DoLayout(self):
448
"""Layout the window"""
449
vsizer = wx.BoxSizer(wx.VERTICAL)
450
vsizer.Add(self._settings, 0, wx.EXPAND|wx.ALL, 5)
451
vsizer.Add(self.preview, 1, wx.EXPAND)
452
self.SetSizer(vsizer)
454
#---- Properties ----#
456
StyleTags = property(lambda self: self._settings.TagList.GetItems(),
457
lambda self, val: self._settings.TagList.SetItems(sorted(val)))
458
SettingsPanel = property(lambda self: self._settings)
460
#---- Public API ----#
462
def ChangeStyleSheet(self, sheet_name):
463
"""Change the style sheet that is being edited
464
@param sheet_name: style sheet name (without extension)
467
self.prebuff.UpdateAllStyles(sheet_name)
468
self.ResetTransientStyleData()
469
tag = self._settings.TagList.GetStringSelection()
470
if tag != wx.EmptyString:
471
self.UpdateSettingsPane(self.styles_new[tag])
233
473
def DiffStyles(self):
234
474
"""Checks if the current style set is different from the
368
539
return u"".join(sty_sheet)
370
def OnCancel(self, evt):
371
"""Catches the cancel button clicks and checks if anything
372
needs to be done before closing the window.
373
@param evt: event that called this handler
376
self.LOG('[style_editor][evt] Cancel Clicked Closing Window')
379
def OnCheck(self, evt):
380
"""Handles Checkbox events
381
@param evt: event that called this handler
385
e_obj = evt.GetEventObject()
386
if e_id == wx.ID_NEW:
387
val = e_obj.GetValue()
388
choice = self.ctrl_pane.FindWindowById(ed_glob.ID_PREF_SYNTHEME)
389
choice.Enable(not val)
391
self.styles_orig = self.preview.BlankStyleDictionary()
392
self.styles_new = DuplicateStyleDict(self.styles_orig)
393
self.preview.SetStyles('preview', self.styles_new, nomerge=True)
394
self.preview.UpdateAllStyles('preview')
396
# For some reason this causes the text display to refresh
397
# properly when nothing else would work.
400
scheme = choice.GetStringSelection().lower()
401
self.preview.UpdateAllStyles(scheme)
402
self.styles_orig = self.preview.GetStyleSet()
403
self.styles_new = DuplicateStyleDict(self.styles_orig)
404
elif e_id in [ID_BOLD, ID_EOL, ID_ULINE, ID_ITALIC]:
405
self.UpdateStyleSet(e_id)
409
def OnChoice(self, evt):
410
"""Handles the events generated from the choice controls
411
@param evt: event that called this handler
415
e_obj = evt.GetEventObject()
416
val = e_obj.GetStringSelection()
417
if e_id == ed_glob.ID_LEXER:
418
self.OpenPreviewFile(val)
419
elif e_id == ed_glob.ID_PREF_SYNTHEME:
420
# TODO Need to check for style changes before switching this
421
self.preview.UpdateAllStyles(val)
422
self.styles_new = self.preview.GetStyleSet()
423
self.styles_orig = DuplicateStyleDict(self.styles_new)
424
ctrl = self.FindWindowById(ID_STYLES)
425
tag = ctrl.GetStringSelection()
426
if tag != wx.EmptyString:
427
self.UpdateSettingsPane(self.styles_new[tag])
428
elif e_id in [ID_FONT, ID_FONT_SIZE]:
429
self.UpdateStyleSet(e_id)
433
def OnClose(self, evt):
434
"""Handles the window closer event
435
@param evt: event that called this handler
438
self.LOG("[style_editor][evt] Dialog closing...")
441
def OnColor(self, evt):
442
"""Handles color selection events
443
@param evt: event that called this handler
446
# Update The Style data for current tag
447
self.UpdateStyleSet(evt.GetId())
449
def OnTextRegion(self, evt=None):
450
"""Processes clicks in the preview control and sets the style
451
selection in the style tags list to the style tag of the area
452
the cursor has moved into.
453
@param evt: event that called this handler
459
style_id = self.preview.GetStyleAt(self.preview.GetCurrentPos())
460
tag_lst = self.FindWindowById(ID_STYLES)
461
data = self.preview.FindTagById(style_id)
462
if data != wx.EmptyString and data in self.styles_new:
463
tag_lst.SetStringSelection(data)
464
if wx.Platform == '__WXGTK__':
465
tag_lst.SetFirstItemStr(data)
466
self.UpdateSettingsPane(self.styles_new[data])
467
self.EnableSettings()
469
def OnListBox(self, evt):
470
"""Catches the selection of a style tag in the listbox
471
and updates the style window appropriately.
472
@param evt: event that called this handler
475
tag = evt.GetEventObject().GetStringSelection()
476
if tag != wx.EmptyString and tag in self.styles_new:
477
self.UpdateSettingsPane(self.styles_new[tag])
478
self.EnableSettings()
480
self.EnableSettings(False)
483
"""Catches the OK button click and checks if any changes need to be
484
saved before the window closes.
485
@param evt: event that called this handler
488
self.LOG('[style_editor][evt] Ok Clicked Closing Window')
491
result = self.DiffStyles()
492
if result == wx.ID_NO:
493
# Get Current Selection to update buffers
494
csheet = self.FindWindowById(ed_glob.ID_PREF_SYNTHEME).GetStringSelection()
495
UpdateBufferStyles(csheet)
497
elif result == wx.ID_CANCEL:
498
self.LOG('[style_editor][info] canceled closing')
500
result = self.ExportStyleSheet()
501
if result != wx.ID_CANCEL:
504
def OnExport(self, evt):
505
"""Catches save button event
506
@param evt: event that called this handler
509
self.LOG('[style_editor][evt] Export Clicked')
510
self.ExportStyleSheet()
512
def OpenPreviewFile(self, file_lbl):
513
"""Opens a file using the names in the Syntax Files choice
514
control as a search query.
515
@param file_lbl: name of file to open in test data directory
518
fname = file_lbl.replace(u" ", u"_").replace(u"/", u"_").lower()
519
fname = fname.replace('#', 'sharp')
521
fname = glob.glob(ed_glob.CONFIG['TEST_DIR'] + fname + ".*")[0]
523
self.LOG('[style_editor][err] File %s Does not exist' % fname)
526
self.preview.SetFileName(fname)
527
self.preview.ClearAll()
528
self.preview.LoadFile(fname)
529
self.preview.FindLexer()
530
self.preview.EmptyUndoBuffer()
541
def ResetTransientStyleData(self):
542
"""Reset the transient style data to mark the changes as not dirty"""
543
self.styles_new = DuplicateStyleDict(self.prebuff.GetStyleSet())
544
self.styles_orig = DuplicateStyleDict(self.styles_new)
546
def SetBlankStyle(self):
547
"""Clear all the transient style data to a blank style set"""
548
self.styles_orig = self.prebuff.BlankStyleDictionary()
549
self.styles_new = DuplicateStyleDict(self.styles_orig)
550
self.prebuff.SetStyles('preview', self.styles_new, nomerge=True)
551
self.prebuff.UpdateAllStyles('preview')
553
# For some reason this causes the text display to refresh
554
# properly when nothing else would work.
533
557
def UpdateSettingsPane(self, syntax_data):
534
558
"""Updates all the settings controls to hold the
690
787
fontenum.EnumerateFacenames(fixedWidthOnly=False)
692
789
fontenum.EnumerateFacenames(fixedWidthOnly=True)
693
font_lst = ["%(primary)s", "%(secondary)s"]
790
font_lst = [u"%(primary)s", u"%(secondary)s"]
694
791
font_lst.extend(sorted(fontenum.GetFacenames()))
695
792
fchoice = wx.Choice(self, ID_FONT, choices=font_lst)
696
793
fsizer.AddMany([((5, 5), 0), (flbl, 0, wx.ALIGN_CENTER_VERTICAL),
697
(fchoice, 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5))])
698
fbox_sizer.Add(fsizer, 0, wx.ALIGN_LEFT)
794
(fchoice, 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5),0)])
795
fbox_sizer.Add(fsizer, 0)
701
798
fsize_sizer = wx.BoxSizer(wx.HORIZONTAL)
702
799
fsize_lbl = wx.StaticText(self, label=_("Size") + u": ")
703
fsizes = ['%(size)d', '%(size2)d']
704
fsizes.extend([ str(x) for x in xrange(4, 21) ])
800
fsizes = [u"%(size)d", u"%(size2)d"]
801
fsizes.extend([ unicode(x) for x in range(4, 21) ])
705
802
fs_choice = wx.Choice(self, ID_FONT_SIZE, choices=fsizes)
706
803
fsize_sizer.AddMany([((5, 5), 0),
707
804
(fsize_lbl, 0, wx.ALIGN_CENTER_VERTICAL),
708
(fs_choice, 1, wx.EXPAND | wx.ALIGN_RIGHT),
805
(fs_choice, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL),
710
fbox_sizer.AddMany([((5, 5)),
711
(fsize_sizer, 0, wx.ALIGN_LEFT | wx.EXPAND)])
712
fh_sizer.AddMany([(fbox_sizer, 0, wx.ALIGN_CENTER_HORIZONTAL),
807
fbox_sizer.AddMany([((5, 5), 0), (fsize_sizer, 0, wx.EXPAND)])
808
fh_sizer.AddMany([(fbox_sizer, 0, wx.ALIGN_CENTER_HORIZONTAL), ((10, 10), 0)])
716
811
setting_sizer.AddMany([(setting_top, 0, wx.ALIGN_CENTER_HORIZONTAL),
717
((10, 10), 1, wx.EXPAND),
718
813
(fh_sizer, 0, wx.ALIGN_CENTER_HORIZONTAL)])
719
self.SetSizer(setting_sizer)
720
self.SetAutoLayout(True)
722
#-----------------------------------------------------------------------------#
815
# Setup Right hand side with the settings controls
816
hsizer.AddStretchSpacer()
817
hsizer.Add(setting_sizer, 0, wx.EXPAND|wx.ALL, 5)
818
hsizer.AddStretchSpacer()
820
self.SetSizer(hsizer)
822
#-----------------------------------------------------------------------------#
824
class PreviewPanel(ed_basewin.EdBaseCtrlBox):
825
"""Panel to hold the preview window and selector"""
826
def __init__(self, parent):
827
super(PreviewPanel, self).__init__(parent)
830
self.LOG = wx.GetApp().GetLog()
831
self.preview = ed_basestc.EditraBaseStc(self, size=(-1, 200),
832
style=wx.SUNKEN_BORDER)
835
self.preview.SetEdgeColumn(80)
836
self.preview.SetEdgeMode(wx.stc.STC_EDGE_LINE)
837
self.preview.SetCaretLineVisible(True)
841
self.Bind(wx.EVT_CHOICE, self.OnChoice)
843
def __DoLayout(self):
844
"""Layout the Panel"""
845
# Create the ControlBar
846
cbar = self.CreateControlBar(wx.TOP)
848
# Setup the ControlBar's controls
849
lexer_lbl = wx.StaticText(cbar, label=_("Preview File") + u": ")
850
lexer_lst = wx.Choice(cbar, ed_glob.ID_LEXER,
851
choices=syntax.GetLexerList())
852
lexer_lst.SetToolTip(wx.ToolTip(_("Set the preview file type")))
853
lexer_lst.SetStringSelection(u"CPP")
854
cbar.AddControl(lexer_lbl)
855
cbar.AddControl(lexer_lst)
857
self.SetWindow(self.preview)
859
def GetPreviewBuffer(self):
860
"""Get the STC instance"""
863
def OnChoice(self, evt):
864
"""Update the preview file"""
865
if evt.GetId() == ed_glob.ID_LEXER:
866
e_obj = evt.GetEventObject()
867
val = e_obj.GetStringSelection()
868
self.OpenPreviewFile(val)
872
def OpenPreviewFile(self, file_lbl):
873
"""Opens a file using the names in the Syntax Files choice
874
control as a search query.
875
@param file_lbl: name of file to open in test data directory
878
fname = file_lbl.replace(u" ", u"_").replace(u"/", u"_").lower()
879
fname = fname.replace('#', 'sharp')
881
fname = glob.glob(ed_glob.CONFIG['TEST_DIR'] + fname + ".*")[0]
883
self.LOG('[style_editor][err] File %s Does not exist' % fname)
886
self.preview.SetFileName(fname)
887
self.preview.ClearAll()
888
self.preview.LoadFile(fname)
889
self.preview.FindLexer()
890
self.preview.EmptyUndoBuffer()
893
#-----------------------------------------------------------------------------#
724
895
def DuplicateStyleDict(style_dict):
725
896
"""Duplicates the style dictionary to make a true copy of
726
897
it, as simply assigning the dictionary to two different variables