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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2896 by schoenebeck, Sun May 1 14:51:55 2016 UTC revision 3566 by schoenebeck, Sat Aug 24 13:42:17 2019 UTC
# Line 1  Line 1 
1  /*  /*
2      Copyright (c) 2014-2016 Christian Schoenebeck      Copyright (c) 2014-2019 Christian Schoenebeck
3            
4      This file is part of "gigedit" and released under the terms of the      This file is part of "gigedit" and released under the terms of the
5      GNU General Public License version 2.      GNU General Public License version 2.
# Line 7  Line 7 
7    
8  #include "scripteditor.h"  #include "scripteditor.h"
9  #include "global.h"  #include "global.h"
10    #include "compat.h"
11    #include <gtk/gtkwidget.h> // for gtk_widget_modify_*()
12    #if defined(__APPLE__)
13    # include "MacHelper.h"
14    #endif
15    #include <math.h> // for log10()
16    
17  #if !USE_LS_SCRIPTVM  #if !USE_LS_SCRIPTVM
18    
19  static const std::string _keywords[] = {  static const std::string _keywords[] = {
20      "on", "end", "declare", "while", "if", "or", "and", "not", "else", "case",      "on", "end", "declare", "while", "if", "or", "and", "not", "else", "case",
21      "select", "to", "const", "polyphonic", "mod"      "select", "to", "const", "polyphonic", "mod", "synchronized"
22  };  };
23  static int _keywordsSz = sizeof(_keywords) / sizeof(std::string);  static int _keywordsSz = sizeof(_keywords) / sizeof(std::string);
24    
# Line 35  static bool isEvent(const Glib::ustring& Line 41  static bool isEvent(const Glib::ustring&
41    
42  #endif // !USE_LS_SCRIPTVM  #endif // !USE_LS_SCRIPTVM
43    
44    static Glib::RefPtr<Gdk::Pixbuf> createIcon(std::string name, const Glib::RefPtr<Gdk::Screen>& screen) {
45        const int targetH = 16;
46        Glib::RefPtr<Gtk::IconTheme> theme = Gtk::IconTheme::get_for_screen(screen);
47        int w = 0;
48        int h = 0; // ignored
49        Gtk::IconSize::lookup(Gtk::ICON_SIZE_SMALL_TOOLBAR, w, h);
50        if (!theme->has_icon(name))
51            return Glib::RefPtr<Gdk::Pixbuf>();
52        Glib::RefPtr<Gdk::Pixbuf> pixbuf = theme->load_icon(name, w, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
53        if (pixbuf->get_height() != targetH) {
54            pixbuf = pixbuf->scale_simple(targetH, targetH, Gdk::INTERP_BILINEAR);
55        }
56        return pixbuf;
57    }
58    
59    static Glib::RefPtr<Gdk::Pixbuf> createIcon(std::vector<std::string> alternativeNames, const Glib::RefPtr<Gdk::Screen>& screen) {
60        for (int i = 0; i < alternativeNames.size(); ++i) {
61            Glib::RefPtr<Gdk::Pixbuf> buf = createIcon(alternativeNames[i], screen);
62            if (buf) return buf;
63        }
64        return Glib::RefPtr<Gdk::Pixbuf>();
65    }
66    
67  ScriptEditor::ScriptEditor() :  ScriptEditor::ScriptEditor() :
68        m_statusLabel("",  Gtk::ALIGN_START),
69    #if HAS_GTKMM_STOCK
70        m_applyButton(Gtk::Stock::APPLY),
71        m_cancelButton(Gtk::Stock::CANCEL)
72    #else
73      m_applyButton(_("_Apply"), true),      m_applyButton(_("_Apply"), true),
74      m_cancelButton(_("_Cancel"), true)      m_cancelButton(_("_Cancel"), true)
75    #endif
76  {  {
77      m_script = NULL;      m_script = NULL;
78  #if USE_LS_SCRIPTVM  #if USE_LS_SCRIPTVM
79      m_vm = NULL;      m_vm = NULL;
80  #endif  #endif
81      m_ignoreEraseEvents = false;  
82        if (!Settings::singleton()->autoRestoreWindowDimension) {
83            set_default_size(800, 700);
84            set_position(Gtk::WIN_POS_MOUSE);
85        }
86    
87        // depending on GTK version and installed themes, there may be different
88        // icons, and different names for them, so for each type of icon we use,
89        // we provide a list of possible icon names, the first one found to be
90        // installed on the local system from the list will be used and loaded for
91        // the respective purpose (so order matters in those lists)
92        //
93        // (see https://developer.gnome.org/gtkmm/stable/namespaceGtk_1_1Stock.html for
94        // available icon names)
95        std::vector<std::string> errorIconNames;
96        errorIconNames.push_back("dialog-error");
97        errorIconNames.push_back("media-record");
98        errorIconNames.push_back("process-stop");
99    
100        std::vector<std::string> warningIconNames;
101        warningIconNames.push_back("dialog-warning-symbolic");
102        warningIconNames.push_back("dialog-warning");
103    
104        std::vector<std::string> successIconNames;
105        successIconNames.push_back("emblem-default");
106        successIconNames.push_back("tools-check-spelling");
107    
108        m_errorIcon = createIcon(errorIconNames, get_screen());
109        m_warningIcon = createIcon(warningIconNames, get_screen());
110        m_successIcon = createIcon(successIconNames, get_screen());
111    
112      add(m_vbox);      add(m_vbox);
113    
# Line 79  ScriptEditor::ScriptEditor() : Line 143  ScriptEditor::ScriptEditor() :
143      m_commentTag->property_foreground() = "#9c9c9c"; // gray      m_commentTag->property_foreground() = "#9c9c9c"; // gray
144      m_tagTable->add(m_commentTag);      m_tagTable->add(m_commentTag);
145    
146        #define PREPROC_TOKEN_COLOR  "#2f8a33" // green
147    
148      m_preprocTag = Gtk::TextBuffer::Tag::create();      m_preprocTag = Gtk::TextBuffer::Tag::create();
149      m_preprocTag->property_foreground() = "#2f8a33"; // green      m_preprocTag->property_foreground() = PREPROC_TOKEN_COLOR;
150      m_tagTable->add(m_preprocTag);      m_tagTable->add(m_preprocTag);
151    
152        m_preprocCommentTag = Gtk::TextBuffer::Tag::create();
153        m_preprocCommentTag->property_strikethrough() = true;
154        m_preprocCommentTag->property_background() = "#e5e5e5";
155        m_tagTable->add(m_preprocCommentTag);
156    
157      m_errorTag = Gtk::TextBuffer::Tag::create();      m_errorTag = Gtk::TextBuffer::Tag::create();
158      m_errorTag->property_background() = "#ff9393"; // red      m_errorTag->property_background() = "#ff9393"; // red
159      m_tagTable->add(m_errorTag);      m_tagTable->add(m_errorTag);
# Line 91  ScriptEditor::ScriptEditor() : Line 162  ScriptEditor::ScriptEditor() :
162      m_warningTag->property_background() = "#fffd7c"; // yellow      m_warningTag->property_background() = "#fffd7c"; // yellow
163      m_tagTable->add(m_warningTag);      m_tagTable->add(m_warningTag);
164    
165      m_readOnlyTag = Gtk::TextBuffer::Tag::create();      m_lineNrTag = Gtk::TextBuffer::Tag::create();
166      m_readOnlyTag->property_editable() = false;      m_lineNrTag->property_foreground() = "#CCCCCC";
167      m_tagTable->add(m_readOnlyTag);      m_tagTable->add(m_lineNrTag);
168    
169        m_metricTag = Gtk::TextBuffer::Tag::create();
170        m_metricTag->property_foreground() = "#000000"; // black
171        m_tagTable->add(m_metricTag);
172    
173        m_stdUnitTag = Gtk::TextBuffer::Tag::create();
174        m_stdUnitTag->property_foreground() = "#50BC00"; // greenish
175        m_tagTable->add(m_stdUnitTag);
176    
177        // create menu
178    #if USE_GTKMM_BUILDER
179        m_actionGroup = Gio::SimpleActionGroup::create();
180        m_actionGroup->add_action(
181            "Apply", sigc::mem_fun(*this, &ScriptEditor::onButtonApply)
182        );
183        m_actionGroup->add_action(
184            "Close", sigc::mem_fun(*this, &ScriptEditor::onButtonCancel)
185        );
186        m_actionGroup->add_action(
187            "ChangeFont", sigc::mem_fun(*this, &ScriptEditor::onMenuChangeFontSize)
188        );
189        insert_action_group("ScriptEditor", m_actionGroup);
190    
191      m_textBuffer = Gtk::TextBuffer::create(m_tagTable);      m_uiManager = Gtk::Builder::create();
192      m_textView.set_buffer(m_textBuffer);      Glib::ustring ui_info =
193            "<interface>"
194            "  <menubar id='MenuBar'>"
195            "    <menu id='MenuScript'>"
196            "      <section>"
197            "        <item id='Apply'>"
198            "          <attribute name='label' translatable='yes'>_Apply</attribute>"
199            "          <attribute name='action'>ScriptEditor.Apply</attribute>"
200            "          <attribute name='accel'>&lt;Primary&gt;s</attribute>"
201            "        </item>"
202            "      </section>"
203            "      <section>"
204            "        <item id='Close'>"
205            "          <attribute name='label' translatable='yes'>_Close</attribute>"
206            "          <attribute name='action'>ScriptEditor.Close</attribute>"
207            "          <attribute name='accel'>&lt;Primary&gt;q</attribute>"
208            "        </item>"
209            "      </section>"
210            "    </menu>"
211            "    <menu id='MenuEditor'>"
212            "      <section>"
213            "        <item id='ChangeFont'>"
214            "          <attribute name='label' translatable='yes'>_Font Size ...</attribute>"
215            "          <attribute name='action'>ScriptEditor.ChangeFont</attribute>"
216            "        </item>"
217            "      </section>"
218            "    </menu>"
219            "  </menubar>"
220            "</interface>";
221        m_uiManager->add_from_string(ui_info);
222        /*{
223            auto object = uiManager->get_object("MenuBar");
224            auto gmenu = Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
225            set_menubar(gmenu);
226        }*/
227    #else
228        m_actionGroup = Gtk::ActionGroup::create();
229        m_actionGroup->add(Gtk::Action::create("MenuScript", _("_Script")));
230        m_actionGroup->add(Gtk::Action::create("Apply", _("_Apply")),
231                           Gtk::AccelKey("<control>s"),
232                           sigc::mem_fun(*this, &ScriptEditor::onButtonApply));
233        m_actionGroup->add(Gtk::Action::create("Close", _("_Close")),
234                           Gtk::AccelKey("<control>q"),
235                           sigc::mem_fun(*this, &ScriptEditor::onButtonCancel));
236        m_actionGroup->add(Gtk::Action::create("MenuEditor", _("_Editor")));
237        m_actionGroup->add(Gtk::Action::create("ChangeFont", _("_Font Size ...")),
238                           sigc::mem_fun(*this, &ScriptEditor::onMenuChangeFontSize));
239        m_uiManager = Gtk::UIManager::create();
240        m_uiManager->insert_action_group(m_actionGroup);
241        add_accel_group(m_uiManager->get_accel_group());
242        m_uiManager->add_ui_from_string(
243            "<ui>"
244            "  <menubar name='MenuBar'>"
245            "    <menu action='MenuScript'>"
246            "      <menuitem action='Apply'/>"
247            "      <separator/>"
248            "      <menuitem action='Close'/>"
249            "    </menu>"
250            "    <menu action='MenuEditor'>"
251            "      <menuitem action='ChangeFont'/>"
252            "    </menu>"
253            "  </menubar>"
254            "</ui>"
255        );
256    #endif
257    
258        m_lineNrBuffer = Gtk::TextBuffer::create(m_tagTable);
259        m_lineNrView.set_size_request(22,14);
260        m_lineNrView.set_buffer(m_lineNrBuffer);
261        m_lineNrView.set_left_margin(3);
262        m_lineNrView.set_right_margin(3);
263        m_lineNrView.property_editable() = false;
264        m_lineNrView.property_sensitive() = false;
265        m_lineNrTextViewSpacer.set_size_request(5,14);
266        m_lineNrTextViewSpacer.property_editable() = false;
267        m_lineNrTextViewSpacer.property_sensitive() = false;
268      {      {
269          Pango::FontDescription fdesc;  #if 1 //(GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
270          fdesc.set_family("monospace");          Gdk::Color color;
 #if defined(__APPLE__)  
         fdesc.set_size(12 * PANGO_SCALE);  
271  #else  #else
272          fdesc.set_size(10 * PANGO_SCALE);          Gdk::RGBA color;
273  #endif  #endif
274  #if GTKMM_MAJOR_VERSION < 3          color.set("#F5F5F5");
275          m_textView.modify_font(fdesc);          GtkWidget* widget = (GtkWidget*) m_lineNrView.gobj();
276    #if GTK_MAJOR_VERSION < 3 || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION <= 24)
277            gtk_widget_modify_base(widget, GTK_STATE_NORMAL, color.gobj());
278            gtk_widget_modify_bg(widget, GTK_STATE_NORMAL, color.gobj());
279    #endif
280        }
281        {
282    #if 1 //(GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
283            Gdk::Color color;
284  #else  #else
285          m_textView.override_font(fdesc);          Gdk::RGBA color;
286    #endif
287            color.set("#EEEEEE");
288            GtkWidget* widget = (GtkWidget*) m_lineNrTextViewSpacer.gobj();
289    #if GTK_MAJOR_VERSION < 3 || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION <= 24)
290            gtk_widget_modify_base(widget, GTK_STATE_NORMAL, color.gobj());
291            gtk_widget_modify_bg(widget, GTK_STATE_NORMAL, color.gobj());
292  #endif  #endif
293      }      }
294      m_scrolledWindow.add(m_textView);      m_textBuffer = Gtk::TextBuffer::create(m_tagTable);
295        m_textView.set_buffer(m_textBuffer);
296        m_textView.set_left_margin(5);
297        setFontSize(currentFontSize(), false);
298        m_textViewHBox.pack_start(m_lineNrView, Gtk::PACK_SHRINK);
299        m_textViewHBox.pack_start(m_lineNrTextViewSpacer, Gtk::PACK_SHRINK);
300        m_textViewHBox.add(m_textView);
301        m_scrolledWindow.add(m_textViewHBox);
302      m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
303    
304    #if USE_GTKMM_BUILDER
305        Gtk::Widget* menuBar = new Gtk::MenuBar(
306            Glib::RefPtr<Gio::Menu>::cast_dynamic(
307                m_uiManager->get_object("MenuBar")
308            )
309        );
310    #else
311        Gtk::Widget* menuBar = m_uiManager->get_widget("/MenuBar");
312    #endif
313    
314        m_vbox.pack_start(*menuBar, Gtk::PACK_SHRINK);
315      m_vbox.pack_start(m_scrolledWindow);      m_vbox.pack_start(m_scrolledWindow);
316    
317      m_buttonBox.set_layout(Gtk::BUTTONBOX_END);      m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
# Line 121  ScriptEditor::ScriptEditor() : Line 320  ScriptEditor::ScriptEditor() :
320      m_applyButton.set_can_default();      m_applyButton.set_can_default();
321      m_applyButton.set_sensitive(false);      m_applyButton.set_sensitive(false);
322      m_applyButton.grab_focus();      m_applyButton.grab_focus();
323      m_vbox.pack_start(m_buttonBox, Gtk::PACK_SHRINK);  
324    #if GTKMM_MAJOR_VERSION < 3
325        m_statusHBox.set_spacing(6);
326    #elif GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION < 12
327        m_statusImage.set_margin_left(6);
328        m_statusImage.set_margin_right(6);
329    #else
330        m_statusImage.set_margin_start(6);
331        m_statusImage.set_margin_end(6);
332    #endif
333    
334        m_statusHBox.pack_start(m_statusImage, Gtk::PACK_SHRINK);
335        m_statusHBox.pack_start(m_statusLabel);
336    #if HAS_GTKMM_SHOW_ALL_CHILDREN
337        m_statusHBox.show_all_children();
338    #endif
339    
340        m_footerHBox.pack_start(m_statusHBox);
341        m_footerHBox.pack_start(m_buttonBox, Gtk::PACK_SHRINK);
342    
343        m_vbox.pack_start(m_footerHBox, Gtk::PACK_SHRINK);
344    
345      m_applyButton.signal_clicked().connect(      m_applyButton.signal_clicked().connect(
346          sigc::mem_fun(*this, &ScriptEditor::onButtonApply)          sigc::mem_fun(*this, &ScriptEditor::onButtonApply)
# Line 147  ScriptEditor::ScriptEditor() : Line 366  ScriptEditor::ScriptEditor() :
366          sigc::mem_fun(*this, &ScriptEditor::onWindowHide)          sigc::mem_fun(*this, &ScriptEditor::onWindowHide)
367      );      );
368    
369      show_all_children();      signal_delete_event().connect(
370    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
371            sigc::mem_fun(*this, &ScriptEditor::onWindowDelete)
372    #else
373            sigc::mem_fun(*this, &ScriptEditor::onWindowDeleteP)
374    #endif
375        );
376    
377      resize(460,300);  #if HAS_GTKMM_SHOW_ALL_CHILDREN
378        show_all_children();
379    #endif
380  }  }
381    
382  ScriptEditor::~ScriptEditor() {  ScriptEditor::~ScriptEditor() {
# Line 159  ScriptEditor::~ScriptEditor() { Line 386  ScriptEditor::~ScriptEditor() {
386  #endif  #endif
387  }  }
388    
389    int ScriptEditor::currentFontSize() const {
390    #if defined(__APPLE__)
391        const int defaultFontSize = 11;
392    #else
393        const int defaultFontSize = 10;
394    #endif
395        const int settingFontSize = Settings::singleton()->scriptEditorFontSize;
396        const int fontSize = (settingFontSize > 0) ? settingFontSize : defaultFontSize;
397        return fontSize;
398    }
399    
400    void ScriptEditor::setFontSize(int sizePt, bool save) {
401        //printf("setFontSize(%d,%d)\n", size, save);
402    
403        // make sure the real size on the screen for the editor's font is consistent
404        // on all screens (which otherwise may vary between models and DPI settings)
405        const double referenceDPI = 96;
406        double dpi = Gdk::Screen::get_default()->get_resolution();
407        double sizePx = sizePt * dpi / referenceDPI;
408    
409    #if GTKMM_MAJOR_VERSION < 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION < 20)
410        Pango::FontDescription fdesc;
411        fdesc.set_family("monospace");
412    # if defined(__APPLE__)
413        // fixes poor readability of default monospace font on Macs
414        if (macIsMinMac10_6())
415            fdesc.set_family("Menlo");
416    # endif
417        fdesc.set_size(sizePx * PANGO_SCALE);
418    # if GTKMM_MAJOR_VERSION < 3
419        m_lineNrView.modify_font(fdesc);
420        m_textView.modify_font(fdesc);
421    # else
422        m_lineNrView.override_font(fdesc);
423        m_textView.override_font(fdesc);
424    # endif
425    #else
426        Glib::ustring family = "monospace";
427    # if defined(__APPLE__)
428        // fixes poor readability of default monospace font on Macs
429        if (macIsMinMac10_6())
430            family = "Menlo";
431    # endif
432        if (!m_css) {
433            m_css = Gtk::CssProvider::create();
434            m_lineNrView.get_style_context()->add_provider(m_css, GTK_STYLE_PROVIDER_PRIORITY_FALLBACK);
435            m_textView.get_style_context()->add_provider(m_css, GTK_STYLE_PROVIDER_PRIORITY_FALLBACK);
436        }
437        m_css->load_from_data(
438            "* {"
439            "  font: " + ToString(sizePt) + "pt " + family + ";"
440            "}"
441        );
442    #endif
443        if (save) Settings::singleton()->scriptEditorFontSize = sizePt;
444    }
445    
446  void ScriptEditor::setScript(gig::Script* script) {  void ScriptEditor::setScript(gig::Script* script) {
447      m_script = script;      m_script = script;
448      if (!script) {      if (!script) {
# Line 172  void ScriptEditor::setScript(gig::Script Line 456  void ScriptEditor::setScript(gig::Script
456      //printf("text : '%s'\n", txt.c_str());      //printf("text : '%s'\n", txt.c_str());
457      m_textBuffer->set_text(txt);      m_textBuffer->set_text(txt);
458      m_textBuffer->set_modified(false);      m_textBuffer->set_modified(false);
459    
460        // on Gtk 3 the respective text change callback would not be called, so force this update here
461        if (txt.empty())
462            updateLineNumbers();
463    }
464    
465    void ScriptEditor::updateLineNumbers() {
466        int n = m_textBuffer->get_line_count();
467        int old = m_lineNrBuffer->get_line_count();
468        if (n == old && old > 1) return;
469        if (n < 1) n = 1;
470        const int digits = log10(n) + 1;
471        const int bufSz = digits + 2;
472        char* buf = new char[bufSz];
473        std::string sFmt1 =   "%" + ToString(digits) + "d";
474        std::string sFmt2 = "\n%" + ToString(digits) + "d";
475        Glib::ustring s;
476        for (int i = 0; i < n; ++i) {
477            snprintf(buf, bufSz, i ? sFmt2.c_str() : sFmt1.c_str(), i+1);
478            s += buf;
479        }
480        m_lineNrBuffer->remove_all_tags(m_lineNrBuffer->begin(), m_lineNrBuffer->end());
481        m_lineNrBuffer->set_text(s);
482        m_lineNrBuffer->apply_tag(m_lineNrTag, m_lineNrBuffer->begin(), m_lineNrBuffer->end());
483        if (buf) delete[] buf;
484  }  }
485    
486  void ScriptEditor::onTextInserted(const Gtk::TextBuffer::iterator& itEnd, const Glib::ustring& txt, int length) {  void ScriptEditor::onTextInserted(const Gtk::TextBuffer::iterator& itEnd, const Glib::ustring& txt, int length) {
487      printf("onTextInserted()\n");      //printf("onTextInserted()\n");
     fflush(stdout);  
488  #if USE_LS_SCRIPTVM  #if USE_LS_SCRIPTVM
     removeIssueAnchors();  
489      m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());      m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());
490      updateSyntaxHighlightingByVM();      updateSyntaxHighlightingByVM();
491      updateParserIssuesByVM();      updateParserIssuesByVM();
492        updateStatusBar();
493  #else  #else
494      //printf("inserted %d\n", length);      //printf("inserted %d\n", length);
495      Gtk::TextBuffer::iterator itStart = itEnd;      Gtk::TextBuffer::iterator itStart = itEnd;
# Line 225  void ScriptEditor::onTextInserted(const Line 533  void ScriptEditor::onTextInserted(const
533      ;      ;
534            
535  #endif // USE_LS_SCRIPTVM  #endif // USE_LS_SCRIPTVM
536        updateLineNumbers();
537  }  }
538    
539  #if USE_LS_SCRIPTVM  #if USE_LS_SCRIPTVM
# Line 234  LinuxSampler::ScriptVM* ScriptEditor::Ge Line 543  LinuxSampler::ScriptVM* ScriptEditor::Ge
543      return m_vm;      return m_vm;
544  }  }
545    
546    template<class T>
547    static void getIteratorsForIssue(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const T& issue, Gtk::TextBuffer::iterator& start, Gtk::TextBuffer::iterator& end) {
548        Gtk::TextBuffer::iterator itLine =
549            txtbuf->get_iter_at_line_index(issue.firstLine - 1, 0);
550        const int charsInLine = itLine.get_bytes_in_line();
551        start = txtbuf->get_iter_at_line_index(
552            issue.firstLine - 1,
553            // check we are not getting past the end of the line here, otherwise Gtk crashes
554            issue.firstColumn - 1 < charsInLine ? issue.firstColumn - 1 : charsInLine - 1
555        );
556        end = start;
557        end.forward_lines(issue.lastLine - issue.firstLine);
558        end.forward_chars(
559            (issue.lastLine != issue.firstLine)
560                ? issue.lastColumn - 1
561                : issue.lastColumn - issue.firstColumn + 1
562        );
563    }
564    
565  static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::VMSourceToken& token, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {  static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::VMSourceToken& token, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {
566      Gtk::TextBuffer::iterator itStart =      Gtk::TextBuffer::iterator itLine =
567          txtbuf->get_iter_at_line_index(token.firstLine(), token.firstColumn());          txtbuf->get_iter_at_line_index(token.firstLine(), 0);
568        const int charsInLine = itLine.get_bytes_in_line();
569        Gtk::TextBuffer::iterator itStart = txtbuf->get_iter_at_line_index(
570            token.firstLine(),
571            // check we are not getting past the end of the line here, otherwise Gtk crashes
572            token.firstColumn() < charsInLine ? token.firstColumn() : charsInLine - 1
573        );
574      Gtk::TextBuffer::iterator itEnd = itStart;      Gtk::TextBuffer::iterator itEnd = itStart;
575      const int length = token.text().length();      const int length = token.text().length();
576      itEnd.forward_chars(length);      itEnd.forward_chars(length);
# Line 244  static void applyCodeTag(Glib::RefPtr<Gt Line 578  static void applyCodeTag(Glib::RefPtr<Gt
578  }  }
579    
580  static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::ParserIssue& issue, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {  static void applyCodeTag(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::ParserIssue& issue, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {
581      Gtk::TextBuffer::iterator itStart =      Gtk::TextBuffer::iterator itStart, itEnd;
582          txtbuf->get_iter_at_line_index(issue.firstLine - 1, issue.firstColumn - 1);      getIteratorsForIssue(txtbuf, issue, itStart, itEnd);
     Gtk::TextBuffer::iterator itEnd = itStart;  
     itEnd.forward_lines(issue.lastLine - issue.firstLine);  
     itEnd.forward_chars(  
         (issue.lastLine != issue.firstLine)  
             ? issue.lastColumn - 1  
             : issue.lastColumn - issue.firstColumn + 1  
     );  
583      txtbuf->apply_tag(tag, itStart, itEnd);      txtbuf->apply_tag(tag, itStart, itEnd);
584  }  }
585    
586  void ScriptEditor::removeIssueAnchors() {  static void applyPreprocessorComment(Glib::RefPtr<Gtk::TextBuffer>& txtbuf, const LinuxSampler::CodeBlock& block, Glib::RefPtr<Gtk::TextBuffer::Tag>& tag) {
587      m_ignoreEraseEvents = true; // avoid endless recursion      Gtk::TextBuffer::iterator itStart, itEnd;
588            getIteratorsForIssue(txtbuf, block, itStart, itEnd);
589      for (int i = 0; i < m_issues.size(); ++i) {      txtbuf->apply_tag(tag, itStart, itEnd);
         const LinuxSampler::ParserIssue& issue = m_issues[i];  
         printf("erase anchor at l%d c%d\n", issue.firstLine - 1, issue.firstColumn - 1);  
         fflush(stdout);  
         Gtk::TextBuffer::iterator iter = m_textBuffer->get_iter_at_line_index(issue.firstLine - 1, issue.firstColumn - 1);  
         Gtk::TextBuffer::iterator iterEnd = iter;  
         iterEnd.forward_chars(1);  
         m_textBuffer->erase(iter, iterEnd);  
     }  
       
     m_ignoreEraseEvents = false; // back to normal  
590  }  }
591    
592  void ScriptEditor::updateSyntaxHighlightingByVM() {  void ScriptEditor::updateSyntaxHighlightingByVM() {
593      GetScriptVM();      GetScriptVM();
594      const std::string s = m_textBuffer->get_text();      const std::string s = m_textBuffer->get_text();
595        if (s.empty()) return;
596      std::vector<LinuxSampler::VMSourceToken> tokens = m_vm->syntaxHighlighting(s);      std::vector<LinuxSampler::VMSourceToken> tokens = m_vm->syntaxHighlighting(s);
597    
598      for (int i = 0; i < tokens.size(); ++i) {      for (int i = 0; i < tokens.size(); ++i) {
# Line 298  void ScriptEditor::updateSyntaxHighlight Line 616  void ScriptEditor::updateSyntaxHighlight
616              applyCodeTag(m_textBuffer, token, m_commentTag);              applyCodeTag(m_textBuffer, token, m_commentTag);
617          } else if (token.isPreprocessor()) {          } else if (token.isPreprocessor()) {
618              applyCodeTag(m_textBuffer, token, m_preprocTag);              applyCodeTag(m_textBuffer, token, m_preprocTag);
619            } else if (token.isMetricPrefix()) {
620                applyCodeTag(m_textBuffer, token, m_metricTag);
621            } else if (token.isStdUnit()) {
622                applyCodeTag(m_textBuffer, token, m_stdUnitTag);
623          } else if (token.isNewLine()) {          } else if (token.isNewLine()) {
624          }          }
625      }      }
626  }  }
627    
 static Glib::RefPtr<Gdk::Pixbuf> createIcon(std::string name, const Glib::RefPtr<Gdk::Screen>& screen) {  
     const int targetH = 9;  
     Glib::RefPtr<Gtk::IconTheme> theme = Gtk::IconTheme::get_for_screen(screen);  
     int w = 0;  
     int h = 0; // ignored  
     Gtk::IconSize::lookup(Gtk::ICON_SIZE_SMALL_TOOLBAR, w, h);  
     Glib::RefPtr<Gdk::Pixbuf> pixbuf = theme->load_icon(name, w, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);  
     if (pixbuf->get_height() != targetH) {  
         pixbuf = pixbuf->scale_simple(targetH, targetH, Gdk::INTERP_BILINEAR);  
     }  
     return pixbuf;  
 }  
   
628  void ScriptEditor::updateParserIssuesByVM() {  void ScriptEditor::updateParserIssuesByVM() {
629      GetScriptVM();      GetScriptVM();
630      const std::string s = m_textBuffer->get_text();      const std::string s = m_textBuffer->get_text();
631      LinuxSampler::VMParserContext* parserContext = m_vm->loadScript(s);      LinuxSampler::VMParserContext* parserContext = m_vm->loadScript(s);
632      m_issues = parserContext->issues();      m_issues = parserContext->issues();
633        m_errors = parserContext->errors();
634        m_warnings = parserContext->warnings();
635        m_preprocComments = parserContext->preprocessorComments();
636    
637        if (!s.empty()) {
638            for (int i = 0; i < m_issues.size(); ++i) {
639                const LinuxSampler::ParserIssue& issue = m_issues[i];
640    
641                if (issue.isErr()) {
642                    applyCodeTag(m_textBuffer, issue, m_errorTag);
643                } else if (issue.isWrn()) {
644                    applyCodeTag(m_textBuffer, issue, m_warningTag);
645                }
646            }
647        }
648    
649        for (int i = 0; i < m_preprocComments.size(); ++i) {
650            applyPreprocessorComment(m_textBuffer, m_preprocComments[i],
651                                     m_preprocCommentTag);
652        }
653    
654        delete parserContext;
655    }
656    
657    void ScriptEditor::updateIssueTooltip(GdkEventMotion* e) {
658        int x, y;
659        m_textView.window_to_buffer_coords(Gtk::TEXT_WINDOW_TEXT, int(e->x), int(e->y), x, y);
660    
661        Gtk::TextBuffer::iterator it;
662        m_textView.get_iter_at_location(it, x, y);
663        
664        const int line = it.get_line();
665        const int column = it.get_line_offset();
666    
667        //printf("mouse at l%d c%d\n", line, column);
668    
669      for (int i = 0; i < m_issues.size(); ++i) {      for (int i = 0; i < m_issues.size(); ++i) {
670          const LinuxSampler::ParserIssue& issue = m_issues[i];          const LinuxSampler::ParserIssue& issue = m_issues[i];
671            const int firstLine   = issue.firstLine - 1;
672          if (issue.isErr()) {          const int firstColumn = issue.firstColumn - 1;
673              applyCodeTag(m_textBuffer, issue, m_errorTag);          const int lastLine    = issue.lastLine - 1;
674          } else if (issue.isWrn()) {          const int lastColumn  = issue.lastColumn - 1;
675              applyCodeTag(m_textBuffer, issue, m_warningTag);          if (firstLine <= line && line <= lastLine &&
676                (firstLine != line || firstColumn <= column) &&
677                (lastLine  != line || lastColumn  >= column))
678            {
679                m_textView.set_tooltip_markup(
680                    (issue.isErr() ? "<span foreground=\"#ff9393\">ERROR:</span> " : "<span foreground=\"#c4950c\">Warning:</span> ") +
681                    issue.txt
682                );
683                return;
684          }          }
685      }      }
686    
687      for (int i = m_issues.size() - 1; i >= 0; --i) {      for (int i = 0; i < m_preprocComments.size(); ++i) {
688          const LinuxSampler::ParserIssue& issue = m_issues[i];          const LinuxSampler::CodeBlock& block = m_preprocComments[i];
689            const int firstLine   = block.firstLine - 1;
690            const int firstColumn = block.firstColumn - 1;
691            const int lastLine    = block.lastLine - 1;
692            const int lastColumn  = block.lastColumn - 1;
693            if (firstLine  <= line && line <= lastLine &&
694                (firstLine != line || firstColumn <= column) &&
695                (lastLine  != line || lastColumn  >= column))
696            {
697                m_textView.set_tooltip_markup(
698                    "Code block filtered out by preceding <span foreground=\"" PREPROC_TOKEN_COLOR "\">preprocessor</span> statement."
699                );
700                return;
701            }
702        }
703    
704          if (issue.isErr() || issue.isWrn()) {      m_textView.set_tooltip_markup("");
705              Glib::RefPtr<Gdk::Pixbuf> pixbuf = createIcon(issue.isErr() ? "dialog-error" : "dialog-warning-symbolic", get_screen());  }
             Gtk::Image* image = Gtk::manage(new Gtk::Image(pixbuf));  
             image->show();  
             Gtk::TextBuffer::iterator iter =  
                 m_textBuffer->get_iter_at_line_index(issue.firstLine - 1, issue.firstColumn - 1);  
             Glib::RefPtr<Gtk::TextChildAnchor> anchor = m_textBuffer->create_child_anchor(iter);  
             m_textView.add_child_at_anchor(*image, anchor);  
               
             iter =  
                 m_textBuffer->get_iter_at_line_index(issue.firstLine - 1, issue.firstColumn - 1);  
             Gtk::TextBuffer::iterator itEnd = iter;  
             itEnd.forward_char();  
706    
707              // prevent that the user can erase the icon with backspace key  static std::string warningsCountTxt(const std::vector<LinuxSampler::ParserIssue> warnings) {
708              m_textBuffer->apply_tag(m_readOnlyTag, iter, itEnd);      std::string txt = "<span foreground=\"#c4950c\">" + ToString(warnings.size());
709        txt += (warnings.size() == 1) ? " Warning" : " Warnings";
710        txt += "</span>";
711        return txt;
712    }
713    
714    static std::string errorsCountTxt(const std::vector<LinuxSampler::ParserIssue> errors) {
715        std::string txt = "<span foreground=\"#c40c0c\">" + ToString(errors.size());
716        txt += (errors.size() == 1) ? " Error" : " Errors";
717        txt += "</span>";
718        return txt;
719    }
720    
721    void ScriptEditor::updateStatusBar() {
722        // update status text
723        std::string txt;
724        if (m_issues.empty()) {
725            txt = "No issues with this script.";
726        } else {
727            const char* txtWontLoad = ". Sampler won't load instruments using this script!";
728            txt = "There ";
729            txt += (m_errors.size() <= 1 && m_warnings.size() <= 1) ? "is " : "are ";
730            if (m_errors.empty()) {
731                txt += warningsCountTxt(m_warnings) + ". Script will load, but might not behave as expected!";
732            } else if (m_warnings.empty()) {
733                txt += errorsCountTxt(m_errors) + txtWontLoad;
734            } else {
735                txt += errorsCountTxt(m_errors) + " and " +
736                       warningsCountTxt(m_warnings) + txtWontLoad;
737          }          }
738      }      }
739        m_statusLabel.set_markup(txt);
740    
741      delete parserContext;      // update status icon
742        m_statusImage.set(
743            m_issues.empty() ? m_successIcon : !m_errors.empty() ? m_errorIcon : m_warningIcon
744        );
745  }  }
746    
747  #endif // USE_LS_SCRIPTVM  #endif // USE_LS_SCRIPTVM
748    
749  void ScriptEditor::onTextErased(const Gtk::TextBuffer::iterator& itStart, const Gtk::TextBuffer::iterator& itEnd) {  void ScriptEditor::onTextErased(const Gtk::TextBuffer::iterator& itStart, const Gtk::TextBuffer::iterator& itEnd) {
750      //printf("erased\n");      //printf("erased\n");
     if (m_ignoreEraseEvents) return;  
   
751  #if USE_LS_SCRIPTVM  #if USE_LS_SCRIPTVM
     removeIssueAnchors();  
752      m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());      m_textBuffer->remove_all_tags(m_textBuffer->begin(), m_textBuffer->end());
753      updateSyntaxHighlightingByVM();      updateSyntaxHighlightingByVM();
754      updateParserIssuesByVM();      updateParserIssuesByVM();
755        updateStatusBar();
756  #else  #else
757      Gtk::TextBuffer::iterator itStart2 = itStart;      Gtk::TextBuffer::iterator itStart2 = itStart;
758      if (itStart2.inside_word() || itStart2.ends_word())      if (itStart2.inside_word() || itStart2.ends_word())
# Line 378  void ScriptEditor::onTextErased(const Gt Line 763  void ScriptEditor::onTextErased(const Gt
763    
764      m_textBuffer->remove_all_tags(itStart2, itEnd2);      m_textBuffer->remove_all_tags(itStart2, itEnd2);
765  #endif // USE_LS_SCRIPTVM  #endif // USE_LS_SCRIPTVM
766        updateLineNumbers();
767    }
768    
769    bool ScriptEditor::on_motion_notify_event(GdkEventMotion* e) {
770    #if USE_LS_SCRIPTVM
771        //TODO: event throttling would be a good idea here
772        updateIssueTooltip(e);
773    #endif
774    #if GTKMM_MAJOR_VERSION < 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION <= 24)
775        return ManagedWindow::on_motion_notify_event(e);
776    #else
777        Gdk::EventMotion em = Glib::wrap(e, true);
778        return ManagedWindow::on_motion_notify_event(em);
779    #endif
780    }
781    
782    void ScriptEditor::onMenuChangeFontSize() {
783        //TODO: for GTKMM >= 3.2 class Gtk::FontChooser could be used instead
784        Gtk::Dialog dialog(_("Font Size"), true /*modal*/);
785        HBox hbox;
786        hbox.set_spacing(6);
787    
788        Gtk::Label label(_("Editor's Font Size:"), Gtk::ALIGN_START);
789        hbox.pack_start(label, Gtk::PACK_SHRINK);
790    
791        Gtk::SpinButton spinButton;
792        spinButton.set_range(4, 80);
793        spinButton.set_increments(1, 10);
794        spinButton.set_value(currentFontSize());
795        hbox.pack_start(spinButton);
796    
797    #if USE_GTKMM_BOX
798        dialog.get_content_area()->pack_start(hbox);
799    #else
800        dialog.get_vbox()->pack_start(hbox);
801    #endif
802        dialog.add_button(_("_OK"), 0);
803        dialog.add_button(_("_Cancel"), 1);
804    
805    #if HAS_GTKMM_SHOW_ALL_CHILDREN
806        dialog.show_all_children();
807    #endif
808    
809        if (!dialog.run()) { // OK selected ...
810            const int newFontSize = spinButton.get_value_as_int();
811            if (newFontSize >= 4)
812                setFontSize(newFontSize, true);
813        }
814    }
815    
816    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
817    bool ScriptEditor::onWindowDelete(Gdk::Event& e) {
818        return onWindowDeleteP(NULL);
819    }
820    #endif
821    
822    bool ScriptEditor::onWindowDeleteP(GdkEventAny* /*e*/) {
823        //printf("onWindowDelete\n");
824    
825        if (!isModified()) return false; // propagate event further (which will close this window)
826    
827        gchar* msg = g_strdup_printf(_("Apply changes to instrument script \"%s\" before closing?"),
828                                     m_script->Name.c_str());
829        Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
830        g_free(msg);
831        dialog.set_secondary_text(_("If you close without applying, your changes will be lost."));
832        dialog.add_button(_("Close _Without Applying"), Gtk::RESPONSE_NO);
833        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
834        dialog.add_button(_("_Apply"), Gtk::RESPONSE_YES);
835        dialog.set_default_response(Gtk::RESPONSE_YES);
836        int response = dialog.run();
837        dialog.hide();
838    
839        // user decided to close script editor without saving
840        if (response == Gtk::RESPONSE_NO)
841            return false; // propagate event further (which will close this window)
842    
843        // user cancelled dialog, thus don't close script editor
844        if (response == Gtk::RESPONSE_CANCEL) {
845            show();
846            return true; // drop event (prevents closing this window)
847        }
848    
849        // user wants to apply the changes, afterwards close window
850        if (response == Gtk::RESPONSE_YES) {
851            onButtonApply();
852            return false; // propagate event further (which will close this window)
853        }
854    
855        // should never ever make it to this point actually
856        return false;
857    }
858    
859    bool ScriptEditor::isModified() const {
860        return m_textBuffer->get_modified();
861  }  }
862    
863  void ScriptEditor::onModifiedChanged() {  void ScriptEditor::onModifiedChanged() {
864      m_applyButton.set_sensitive( m_textBuffer->get_modified() );      m_applyButton.set_sensitive(isModified());
865    #if USE_LS_SCRIPTVM
866        updateStatusBar();
867    #endif
868  }  }
869    
870  void ScriptEditor::onButtonCancel() {  void ScriptEditor::onButtonCancel() {
871        bool dropEvent = onWindowDeleteP(NULL);
872        if (dropEvent) return;
873      hide();      hide();
874  }  }
875    
876  void ScriptEditor::onButtonApply() {  void ScriptEditor::onButtonApply() {
877        signal_script_to_be_changed.emit(m_script);
878      m_script->SetScriptAsText(m_textBuffer->get_text());      m_script->SetScriptAsText(m_textBuffer->get_text());
879        signal_script_changed.emit(m_script);
880      m_textBuffer->set_modified(false);      m_textBuffer->set_modified(false);
881  }  }
882    

Legend:
Removed from v.2896  
changed lines
  Added in v.3566

  ViewVC Help
Powered by ViewVC