/[svn]/gigedit/trunk/src/gigedit/scripteditor.cpp
ViewVC logotype

Contents of /gigedit/trunk/src/gigedit/scripteditor.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2928 - (show annotations) (download)
Fri Jul 1 14:09:25 2016 UTC (3 years, 9 months ago) by schoenebeck
File size: 19607 byte(s)
* Script Editor: Fixed editor which did not appear on some systems due
  to missing icons (using now lists of alternative icon names).
* Bumped version (1.0.0.svn17).

1 /*
2 Copyright (c) 2014-2016 Christian Schoenebeck
3
4 This file is part of "gigedit" and released under the terms of the
5 GNU General Public License version 2.
6 */
7
8 #include "scripteditor.h"
9 #include "global.h"
10
11 #if !USE_LS_SCRIPTVM
12
13 static const std::string _keywords[] = {
14 "on", "end", "declare", "while", "if", "or", "and", "not", "else", "case",
15 "select", "to", "const", "polyphonic", "mod"
16 };
17 static int _keywordsSz = sizeof(_keywords) / sizeof(std::string);
18
19 static const std::string _eventNames[] = {
20 "init", "note", "release", "controller"
21 };
22 static int _eventNamesSz = sizeof(_eventNames) / sizeof(std::string);
23
24 static bool isKeyword(const Glib::ustring& s) {
25 for (int i = 0; i < _keywordsSz; ++i)
26 if (_keywords[i] == s) return true;
27 return false;
28 }
29
30 static bool isEvent(const Glib::ustring& s) {
31 for (int i = 0; i < _eventNamesSz; ++i)
32 if (_eventNames[i] == s) return true;
33 return false;
34 }
35
36 #endif // !USE_LS_SCRIPTVM
37
38 static Glib::RefPtr<Gdk::Pixbuf> createIcon(std::string name, const Glib::RefPtr<Gdk::Screen>& screen) {
39 const int targetH = 16;
40 Glib::RefPtr<Gtk::IconTheme> theme = Gtk::IconTheme::get_for_screen(screen);
41 int w = 0;
42 int h = 0; // ignored
43 Gtk::IconSize::lookup(Gtk::ICON_SIZE_SMALL_TOOLBAR, w, h);
44 if (!theme->has_icon(name))
45 return Glib::RefPtr<Gdk::Pixbuf>();
46 Glib::RefPtr<Gdk::Pixbuf> pixbuf = theme->load_icon(name, w, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
47 if (pixbuf->get_height() != targetH) {
48 pixbuf = pixbuf->scale_simple(targetH, targetH, Gdk::INTERP_BILINEAR);
49 }
50 return pixbuf;
51 }
52
53 static Glib::RefPtr<Gdk::Pixbuf> createIcon(std::vector<std::string> alternativeNames, const Glib::RefPtr<Gdk::Screen>& screen) {
54 for (int i = 0; i < alternativeNames.size(); ++i) {
55 Glib::RefPtr<Gdk::Pixbuf> buf = createIcon(alternativeNames[i], screen);
56 if (buf) return buf;
57 }
58 return Glib::RefPtr<Gdk::Pixbuf>();
59 }
60
61 ScriptEditor::ScriptEditor() :
62 m_statusLabel("", Gtk::ALIGN_START),
63 m_applyButton(_("_Apply"), true),
64 m_cancelButton(_("_Cancel"), true)
65 {
66 m_script = NULL;
67 #if USE_LS_SCRIPTVM
68 m_vm = NULL;
69 #endif
70
71 // depending on GTK version and installed themes, there may be different
72 // icons, and different names for them, so for each type of icon we use,
73 // we provide a list of possible icon names, the first one found to be
74 // installed on the local system from the list will be used and loaded for
75 // the respective purpose (so order matters in those lists)
76 //
77 // (see https://developer.gnome.org/gtkmm/stable/namespaceGtk_1_1Stock.html for
78 // available icon names)
79 std::vector<std::string> errorIconNames;
80 errorIconNames.push_back("dialog-error");
81 errorIconNames.push_back("media-record");
82 errorIconNames.push_back("process-stop");
83
84 std::vector<std::string> warningIconNames;
85 warningIconNames.push_back("dialog-warning-symbolic");
86 warningIconNames.push_back("dialog-warning");
87
88 std::vector<std::string> successIconNames;
89 successIconNames.push_back("emblem-default");
90 successIconNames.push_back("tools-check-spelling");
91
92 m_errorIcon = createIcon(errorIconNames, get_screen());
93 m_warningIcon = createIcon(warningIconNames, get_screen());
94 m_successIcon = createIcon(successIconNames, get_screen());
95
96 add(m_vbox);
97
98 m_tagTable = Gtk::TextBuffer::TagTable::create();
99
100 m_keywordTag = Gtk::TextBuffer::Tag::create();
101 m_keywordTag->property_foreground() = "#000000"; // black
102 m_keywordTag->property_weight() = PANGO_WEIGHT_BOLD;
103 m_tagTable->add(m_keywordTag);
104
105 m_eventTag = Gtk::TextBuffer::Tag::create();
106 m_eventTag->property_foreground() = "#07c0cf"; // cyan 1
107 m_eventTag->property_weight() = PANGO_WEIGHT_BOLD;
108 m_tagTable->add(m_eventTag);
109
110 m_variableTag = Gtk::TextBuffer::Tag::create();
111 m_variableTag->property_foreground() = "#790cc4"; // magenta
112 m_tagTable->add(m_variableTag);
113
114 m_functionTag = Gtk::TextBuffer::Tag::create();
115 m_functionTag->property_foreground() = "#1ba1dd"; // cyan 2
116 m_tagTable->add(m_functionTag);
117
118 m_numberTag = Gtk::TextBuffer::Tag::create();
119 m_numberTag->property_foreground() = "#c4950c"; // yellow
120 m_tagTable->add(m_numberTag);
121
122 m_stringTag = Gtk::TextBuffer::Tag::create();
123 m_stringTag->property_foreground() = "#c40c0c"; // red
124 m_tagTable->add(m_stringTag);
125
126 m_commentTag = Gtk::TextBuffer::Tag::create();
127 m_commentTag->property_foreground() = "#9c9c9c"; // gray
128 m_tagTable->add(m_commentTag);
129
130 m_preprocTag = Gtk::TextBuffer::Tag::create();
131 m_preprocTag->property_foreground() = "#2f8a33"; // green
132 m_tagTable->add(m_preprocTag);
133
134 m_errorTag = Gtk::TextBuffer::Tag::create();
135 m_errorTag->property_background() = "#ff9393"; // red
136 m_tagTable->add(m_errorTag);
137
138 m_warningTag = Gtk::TextBuffer::Tag::create();
139 m_warningTag->property_background() = "#fffd7c"; // yellow
140 m_tagTable->add(m_warningTag);
141
142 // create menu
143 m_actionGroup = Gtk::ActionGroup::create();
144 m_actionGroup->add(Gtk::Action::create("MenuScript", _("_Script")));
145 m_actionGroup->add(Gtk::Action::create("Apply", _("_Apply")),
146 Gtk::AccelKey("<control>s"),
147 sigc::mem_fun(*this, &ScriptEditor::onButtonApply));
148 m_actionGroup->add(Gtk::Action::create("Close", _("_Close")),
149 Gtk::AccelKey("<control>q"),
150 sigc::mem_fun(*this, &ScriptEditor::onButtonCancel));
151 m_uiManager = Gtk::UIManager::create();
152 m_uiManager->insert_action_group(m_actionGroup);
153 add_accel_group(m_uiManager->get_accel_group());
154 m_uiManager->add_ui_from_string(
155 "<ui>"
156 " <menubar name='MenuBar'>"
157 " <menu action='MenuScript'>"
158 " <menuitem action='Apply'/>"
159 " <separator/>"
160 " <menuitem action='Close'/>"
161 " </menu>"
162 " </menubar>"
163 "</ui>"
164 );
165
166 m_textBuffer = Gtk::TextBuffer::create(m_tagTable);
167 m_textView.set_buffer(m_textBuffer);
168 {
169 Pango::FontDescription fdesc;
170 fdesc.set_family("monospace");
171 #if defined(__APPLE__)
172 fdesc.set_size(12 * PANGO_SCALE);
173 #else
174 fdesc.set_size(10 * PANGO_SCALE);
175 #endif
176 #if GTKMM_MAJOR_VERSION < 3
177 m_textView.modify_font(fdesc);
178 #else
179 m_textView.override_font(fdesc);
180 #endif
181 }
182 m_scrolledWindow.add(m_textView);
183 m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
184
185 Gtk::Widget* menuBar = m_uiManager->get_widget("/MenuBar");
186 m_vbox.pack_start(*menuBar, Gtk::PACK_SHRINK);
187 m_vbox.pack_start(m_scrolledWindow);
188
189 m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
190 m_buttonBox.pack_start(m_applyButton);
191 m_buttonBox.pack_start(m_cancelButton);
192 m_applyButton.set_can_default();
193 m_applyButton.set_sensitive(false);
194 m_applyButton.grab_focus();
195
196 #if GTKMM_MAJOR_VERSION >= 3
197 m_statusImage.set_margin_left(6);
198 m_statusImage.set_margin_right(6);
199 #else
200 m_statusHBox.set_spacing(6);
201 #endif
202
203 m_statusHBox.pack_start(m_statusImage, Gtk::PACK_SHRINK);
204 m_statusHBox.pack_start(m_statusLabel);
205 m_statusHBox.show_all_children();
206
207 m_footerHBox.pack_start(m_statusHBox);
208 m_footerHBox.pack_start(m_buttonBox, Gtk::PACK_SHRINK);
209
210 m_vbox.pack_start(m_footerHBox, Gtk::PACK_SHRINK);
211
212 m_applyButton.signal_clicked().connect(
213 sigc::mem_fun(*this, &ScriptEditor::onButtonApply)
214 );
215
216 m_cancelButton.signal_clicked().connect(
217 sigc::mem_fun(*this, &ScriptEditor::onButtonCancel)
218 );
219
220 m_textBuffer->signal_insert().connect(
221 sigc::mem_fun(*this, &ScriptEditor::onTextInserted)
222 );
223
224 m_textBuffer->signal_erase().connect(
225 sigc::mem_fun(*this, &ScriptEditor::onTextErased)
226 );
227
228 m_textBuffer->signal_modified_changed().connect(
229 sigc::mem_fun(*this, &ScriptEditor::onModifiedChanged)
230 );
231
232 signal_hide().connect(
233 sigc::mem_fun(*this, &ScriptEditor::onWindowHide)
234 );
235
236 signal_delete_event().connect(
237 sigc::mem_fun(*this, &ScriptEditor::onWindowDelete)
238 );
239
240 show_all_children();
241 }
242
243 ScriptEditor::~ScriptEditor() {
244 printf("ScriptEditor destruct\n");
245 #if USE_LS_SCRIPTVM
246 if (m_vm) delete m_vm;
247 #endif
248 }
249
250 void ScriptEditor::setScript(gig::Script* script) {
251 m_script = script;
252 if (!script) {
253 set_title(_("No Script"));
254 return;
255 }
256
257 set_title(std::string(_("Instrument Script")) + " - \"" + script->Name + "\"");
258
259 std::string txt = script->GetScriptAsText();
260 //printf("text : '%s'\n", txt.c_str());
261 m_textBuffer->set_text(txt);
262 m_textBuffer->set_modified(false);
263 }
264
265 void ScriptEditor::onTextInserted(const Gtk::TextBuffer::iterator& itEnd, const Glib::ustring& txt, int length) {
266 //printf("onTextInserted()\n");
267 #if USE_LS_SCRIPTVM
268 m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());
269 updateSyntaxHighlightingByVM();
270 updateParserIssuesByVM();
271 updateStatusBar();
272 #else
273 //printf("inserted %d\n", length);
274 Gtk::TextBuffer::iterator itStart = itEnd;
275 itStart.backward_chars(length);
276
277 Gtk::TextBuffer::iterator it = itStart;
278 it.backward_word_start();
279
280 bool eofReached = false;
281 while (it <= itEnd) {
282 Gtk::TextBuffer::iterator itWordStart = it;
283 if (!it.forward_word_end()) {
284 eofReached = true;
285 it = itEnd;
286 }
287
288 Glib::ustring s = m_textBuffer->get_text(itWordStart, it, false);
289 //printf("{%s}\n", s.c_str());
290 if (isKeyword(s))
291 m_textBuffer->apply_tag(m_keywordTag, itWordStart, it);
292 else if (isEvent(s)) {
293 // check if previous word is "on"
294 Gtk::TextBuffer::iterator itPreviousWordStart = itWordStart;
295 if (itPreviousWordStart.backward_word_start()) {
296 Gtk::TextBuffer::iterator itPreviousWordEnd = itPreviousWordStart;
297 itPreviousWordEnd.forward_word_end();
298 if (m_textBuffer->get_text(itPreviousWordStart, itPreviousWordEnd, false) == "on") {
299 m_textBuffer->apply_tag(m_eventTag, itWordStart, it);
300 }
301 }
302 }
303
304 if (eofReached) break;
305
306 while (!it.inside_word())
307 if (!it.forward_char())
308 goto EOF_REACHED;
309 }
310
311 EOF_REACHED:
312 ;
313
314 #endif // USE_LS_SCRIPTVM
315 }
316
317 #if USE_LS_SCRIPTVM
318
319 LinuxSampler::ScriptVM* ScriptEditor::GetScriptVM() {
320 if (!m_vm) m_vm = LinuxSampler::ScriptVMFactory::Create("gig");
321 return m_vm;
322 }
323
324 static void getIteratorsForIssue(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::ParserIssue& issue, Gtk::TextBuffer::iterator& start, Gtk::TextBuffer::iterator& end) {
325 start = txtbuf->get_iter_at_line_index(issue.firstLine - 1, issue.firstColumn - 1);
326 end = start;
327 end.forward_lines(issue.lastLine - issue.firstLine);
328 end.forward_chars(
329 (issue.lastLine != issue.firstLine)
330 ? issue.lastColumn - 1
331 : issue.lastColumn - issue.firstColumn + 1
332 );
333 }
334
335 static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::VMSourceToken& token, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {
336 Gtk::TextBuffer::iterator itStart =
337 txtbuf->get_iter_at_line_index(token.firstLine(), token.firstColumn());
338 Gtk::TextBuffer::iterator itEnd = itStart;
339 const int length = token.text().length();
340 itEnd.forward_chars(length);
341 txtbuf->apply_tag(tag, itStart, itEnd);
342 }
343
344 static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::ParserIssue& issue, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {
345 Gtk::TextBuffer::iterator itStart, itEnd;
346 getIteratorsForIssue(txtbuf, issue, itStart, itEnd);
347 txtbuf->apply_tag(tag, itStart, itEnd);
348 }
349
350 void ScriptEditor::updateSyntaxHighlightingByVM() {
351 GetScriptVM();
352 const std::string s = m_textBuffer->get_text();
353 std::vector<LinuxSampler::VMSourceToken> tokens = m_vm->syntaxHighlighting(s);
354
355 for (int i = 0; i < tokens.size(); ++i) {
356 const LinuxSampler::VMSourceToken& token = tokens[i];
357
358 if (token.isKeyword()) {
359 applyCodeTag(m_textBuffer, token, m_keywordTag);
360 } else if (token.isVariableName()) {
361 applyCodeTag(m_textBuffer, token, m_variableTag);
362 } else if (token.isIdentifier()) {
363 if (token.isEventHandlerName()) {
364 applyCodeTag(m_textBuffer, token, m_eventTag);
365 } else { // a function ...
366 applyCodeTag(m_textBuffer, token, m_functionTag);
367 }
368 } else if (token.isNumberLiteral()) {
369 applyCodeTag(m_textBuffer, token, m_numberTag);
370 } else if (token.isStringLiteral()) {
371 applyCodeTag(m_textBuffer, token, m_stringTag);
372 } else if (token.isComment()) {
373 applyCodeTag(m_textBuffer, token, m_commentTag);
374 } else if (token.isPreprocessor()) {
375 applyCodeTag(m_textBuffer, token, m_preprocTag);
376 } else if (token.isNewLine()) {
377 }
378 }
379 }
380
381 void ScriptEditor::updateParserIssuesByVM() {
382 GetScriptVM();
383 const std::string s = m_textBuffer->get_text();
384 LinuxSampler::VMParserContext* parserContext = m_vm->loadScript(s);
385 m_issues = parserContext->issues();
386 m_errors = parserContext->errors();
387 m_warnings = parserContext->warnings();
388
389 for (int i = 0; i < m_issues.size(); ++i) {
390 const LinuxSampler::ParserIssue& issue = m_issues[i];
391
392 if (issue.isErr()) {
393 applyCodeTag(m_textBuffer, issue, m_errorTag);
394 } else if (issue.isWrn()) {
395 applyCodeTag(m_textBuffer, issue, m_warningTag);
396 }
397 }
398
399 delete parserContext;
400 }
401
402 void ScriptEditor::updateIssueTooltip(GdkEventMotion* e) {
403 int x, y;
404 m_textView.window_to_buffer_coords(Gtk::TEXT_WINDOW_TEXT, int(e->x), int(e->y), x, y);
405
406 Gtk::TextBuffer::iterator it;
407 m_textView.get_iter_at_location(it, x, y);
408
409 const int line = it.get_line();
410 const int column = it.get_line_offset();
411
412 //printf("mouse at l%d c%d\n", line, column);
413
414 for (int i = 0; i < m_issues.size(); ++i) {
415 const LinuxSampler::ParserIssue& issue = m_issues[i];
416 const int firstLine = issue.firstLine - 1;
417 const int firstColumn = issue.firstColumn - 1;
418 const int lastLine = issue.lastLine - 1;
419 const int lastColumn = issue.lastColumn - 1;
420 if (firstLine <= line && line <= lastLine &&
421 (firstLine != line || firstColumn <= column) &&
422 (lastLine != line || lastColumn >= column))
423 {
424 m_textView.set_tooltip_markup(
425 (issue.isErr() ? "<span foreground=\"#ff9393\">ERROR:</span> " : "<span foreground=\"#c4950c\">Warning:</span> ") +
426 issue.txt
427 );
428 return;
429 }
430 }
431
432 m_textView.set_tooltip_markup("");
433 }
434
435 static std::string warningsCountTxt(const std::vector<LinuxSampler::ParserIssue> warnings) {
436 std::string txt = "<span foreground=\"#c4950c\">" + ToString(warnings.size());
437 txt += (warnings.size() == 1) ? " Warning" : " Warnings";
438 txt += "</span>";
439 return txt;
440 }
441
442 static std::string errorsCountTxt(const std::vector<LinuxSampler::ParserIssue> errors) {
443 std::string txt = "<span foreground=\"#c40c0c\">" + ToString(errors.size());
444 txt += (errors.size() == 1) ? " Error" : " Errors";
445 txt += "</span>";
446 return txt;
447 }
448
449 void ScriptEditor::updateStatusBar() {
450 // update status text
451 std::string txt;
452 if (m_issues.empty()) {
453 txt = "No issues with this script.";
454 } else {
455 const char* txtWontLoad = ". Sampler won't load instruments using this script!";
456 txt = "There ";
457 txt += (m_errors.size() <= 1 && m_warnings.size() <= 1) ? "is " : "are ";
458 if (m_errors.empty()) {
459 txt += warningsCountTxt(m_warnings) + ". Script will load, but might not behave as expected!";
460 } else if (m_warnings.empty()) {
461 txt += errorsCountTxt(m_errors) + txtWontLoad;
462 } else {
463 txt += errorsCountTxt(m_errors) + " and " +
464 warningsCountTxt(m_warnings) + txtWontLoad;
465 }
466 }
467 m_statusLabel.set_markup(txt);
468
469 // update status icon
470 m_statusImage.set(
471 m_issues.empty() ? m_successIcon : !m_errors.empty() ? m_errorIcon : m_warningIcon
472 );
473 }
474
475 #endif // USE_LS_SCRIPTVM
476
477 void ScriptEditor::onTextErased(const Gtk::TextBuffer::iterator& itStart, const Gtk::TextBuffer::iterator& itEnd) {
478 //printf("erased\n");
479 #if USE_LS_SCRIPTVM
480 m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());
481 updateSyntaxHighlightingByVM();
482 updateParserIssuesByVM();
483 updateStatusBar();
484 #else
485 Gtk::TextBuffer::iterator itStart2 = itStart;
486 if (itStart2.inside_word() || itStart2.ends_word())
487 itStart2.backward_word_start();
488
489 Gtk::TextBuffer::iterator itEnd2 = itEnd;
490 if (itEnd2.inside_word()) itEnd2.forward_word_end();
491
492 m_textBuffer->remove_all_tags(itStart2, itEnd2);
493 #endif // USE_LS_SCRIPTVM
494 }
495
496 bool ScriptEditor::on_motion_notify_event(GdkEventMotion* e) {
497 #if USE_LS_SCRIPTVM
498 //TODO: event throttling would be a good idea here
499 updateIssueTooltip(e);
500 #endif
501 return ManagedWindow::on_motion_notify_event(e);
502 }
503
504 bool ScriptEditor::onWindowDelete(GdkEventAny* e) {
505 //printf("onWindowDelete\n");
506
507 if (!isModified()) return false; // propagate event further (which will close this window)
508
509 gchar* msg = g_strdup_printf(_("Apply changes to instrument script \"%s\" before closing?"),
510 m_script->Name.c_str());
511 Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
512 g_free(msg);
513 dialog.set_secondary_text(_("If you close without applying, your changes will be lost."));
514 dialog.add_button(_("Close _Without Applying"), Gtk::RESPONSE_NO);
515 dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
516 dialog.add_button(_("_Apply"), Gtk::RESPONSE_YES);
517 dialog.set_default_response(Gtk::RESPONSE_YES);
518 int response = dialog.run();
519 dialog.hide();
520
521 // user decided to close script editor without saving
522 if (response == Gtk::RESPONSE_NO)
523 return false; // propagate event further (which will close this window)
524
525 // user cancelled dialog, thus don't close script editor
526 if (response == Gtk::RESPONSE_CANCEL) {
527 show();
528 return true; // drop event (prevents closing this window)
529 }
530
531 // user wants to apply the changes, afterwards close window
532 if (response == Gtk::RESPONSE_YES) {
533 onButtonApply();
534 return false; // propagate event further (which will close this window)
535 }
536
537 // should never ever make it to this point actually
538 return false;
539 }
540
541 bool ScriptEditor::isModified() const {
542 return m_textBuffer->get_modified();
543 }
544
545 void ScriptEditor::onModifiedChanged() {
546 m_applyButton.set_sensitive(isModified());
547 #if USE_LS_SCRIPTVM
548 updateStatusBar();
549 #endif
550 }
551
552 void ScriptEditor::onButtonCancel() {
553 bool dropEvent = onWindowDelete(NULL);
554 if (dropEvent) return;
555 hide();
556 }
557
558 void ScriptEditor::onButtonApply() {
559 signal_script_to_be_changed.emit(m_script);
560 m_script->SetScriptAsText(m_textBuffer->get_text());
561 signal_script_changed.emit(m_script);
562 m_textBuffer->set_modified(false);
563 }
564
565 void ScriptEditor::onWindowHide() {
566 delete this; // this is the end, my friend
567 }

  ViewVC Help
Powered by ViewVC