mainwindow.cc 38.5 KB
Newer Older
1 2
/*
 * Copyright (c) 2002-2007  Daniel Elstner  <daniel.kitta@gmail.com>
3
 *
4
 * This file is part of regexxer.
5
 *
6 7 8 9
 * regexxer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
10
 *
11
 * regexxer is distributed in the hope that it will be useful,
12 13 14 15 16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
17 18
 * along with regexxer; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
 */
daniel_e's avatar
daniel_e committed
20 21

#include "mainwindow.h"
22
#include "filetree.h"
23
#include "globalstrings.h"
24
#include "prefdialog.h"
25
#include "statusline.h"
daniel_e's avatar
daniel_e committed
26
#include "stringutils.h"
27
#include "translation.h"
28
#include "settings.h"
daniel_e's avatar
daniel_e committed
29

30
#include <glib.h>
daniel_e's avatar
daniel_e committed
31
#include <gtkmm.h>
32
#include <gtksourceviewmm.h>
33
#include <algorithm>
34
#include <functional>
35
#include <iostream>
daniel_e's avatar
daniel_e committed
36 37 38 39 40 41

#include <config.h>

namespace
{

42
enum { BUSY_GUI_UPDATE_INTERVAL = 16 };
43

daniel_e's avatar
daniel_e committed
44 45
typedef Glib::RefPtr<Regexxer::FileBuffer> FileBufferPtr;

46
static const char *const selection_clipboard = "CLIPBOARD";
47

48 49 50
/*
 * List of authors to be displayed in the about dialog.
 */
51
static const char *const program_authors[] =
52 53
{
  "Daniel Elstner <daniel.kitta@gmail.com>",
Fabien Parent's avatar
Fabien Parent committed
54
  "Fabien Parent <parent.f@gmail.com>",
55 56 57
  "Murray Cumming <murrayc@murrayc.com>",
  0
};
daniel_e's avatar
daniel_e committed
58

59
static const char *const program_license =
60 61 62 63 64 65 66 67 68 69 70 71
  "regexxer is free software; you can redistribute it and/or modify "
  "it under the terms of the GNU General Public License as published by "
  "the Free Software Foundation; either version 2 of the License, or "
  "(at your option) any later version.\n"
  "\n"
  "regexxer is distributed in the hope that it will be useful, "
  "but WITHOUT ANY WARRANTY; without even the implied warranty of "
  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the "
  "GNU General Public License for more details.\n"
  "\n"
  "You should have received a copy of the GNU General Public License "
  "along with regexxer; if not, write to the Free Software Foundation, "
72
  "Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n";
73

74
class FileErrorDialog : public Gtk::MessageDialog
75 76
{
public:
77
  FileErrorDialog(Gtk::Window& parent, const Glib::ustring& message,
78
                  Gtk::MessageType type, const Regexxer::FileTree::Error& error);
79
  virtual ~FileErrorDialog();
80 81
};

82
FileErrorDialog::FileErrorDialog(Gtk::Window& parent, const Glib::ustring& message,
83
                                 Gtk::MessageType type, const Regexxer::FileTree::Error& error)
84
:
85
  Gtk::MessageDialog(parent, message, false, type, Gtk::BUTTONS_OK, true)
86 87 88 89 90 91
{
  using namespace Gtk;

  const Glib::RefPtr<TextBuffer> buffer = TextBuffer::create();
  TextBuffer::iterator buffer_end = buffer->end();

92
  typedef std::list<Glib::ustring> ErrorList;
93 94
  const ErrorList& error_list = error.get_error_list();

95 96
  for (ErrorList::const_iterator perr = error_list.begin(); perr != error_list.end(); ++perr)
    buffer_end = buffer->insert(buffer_end, *perr + '\n');
97

98
  Box& box = *get_vbox();
99
  Frame *const frame = new Frame();
100
  box.pack_start(*manage(frame), PACK_EXPAND_WIDGET);
101
  frame->set_border_width(6); // HIG spacing
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  frame->set_shadow_type(SHADOW_IN);

  ScrolledWindow *const scrollwin = new ScrolledWindow();
  frame->add(*manage(scrollwin));
  scrollwin->set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC);

  TextView *const textview = new TextView(buffer);
  scrollwin->add(*manage(textview));
  textview->set_editable(false);
  textview->set_cursor_visible(false);
  textview->set_wrap_mode(WRAP_WORD);
  textview->set_pixels_below_lines(8);

  set_default_size(400, 250);
  frame->show_all();
}

119
FileErrorDialog::~FileErrorDialog()
120 121
{}

122
static
123 124 125 126 127 128 129 130 131 132 133 134 135 136
void print_location(int linenumber, const Glib::ustring& subject, Regexxer::FileInfoPtr fileinfo)
{
  std::cout << fileinfo->fullname << ':' << linenumber + 1 << ':';

  std::string charset;

  if (Glib::get_charset(charset))
    std::cout << subject.raw(); // charset is UTF-8
  else
    std::cout << Glib::convert_with_fallback(subject.raw(), charset, "UTF-8");

  std::cout << std::endl;
}

daniel_e's avatar
daniel_e committed
137 138 139 140 141
} // anonymous namespace

namespace Regexxer
{

142 143 144 145
/**** Regexxer::InitState **************************************************/

InitState::InitState()
:
146 147
  folder        (),
  pattern       (),
148 149
  regex         (),
  substitution  (),
150
  no_recursive  (false),
151
  hidden        (false),
152
  no_global     (false),
153
  ignorecase    (false),
154
  feedback      (false),
155
  no_autorun    (false)
156 157 158 159 160
{}

InitState::~InitState()
{}

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
/**** Regexxer::MainWindow::BusyAction *************************************/

class MainWindow::BusyAction
{
private:
  MainWindow& object_;

  BusyAction(const BusyAction&);
  BusyAction& operator=(const BusyAction&);

public:
  explicit BusyAction(MainWindow& object)
    : object_ (object) { object_.busy_action_enter(); }

  ~BusyAction() { object_.busy_action_leave(); }
};

/**** Regexxer::MainWindow *************************************************/

daniel_e's avatar
daniel_e committed
180 181
MainWindow::MainWindow()
:
182 183
  headerbar_              (0),
  button_gear_            (0),
184
  grid_file_              (0),
185
  button_folder_          (0),
186
  combo_entry_pattern_    (Gtk::manage(new Gtk::ComboBoxText(true))),
187 188 189
  button_recursive_       (0),
  button_hidden_          (0),
  entry_regex_            (0),
190
  entry_regex_completion_stack_(10, Settings::instance()->get_string_array(conf_key_regex_patterns)),
191
  entry_regex_completion_ (Gtk::EntryCompletion::create()),
192
  entry_substitution_     (0),
193
  entry_substitution_completion_stack_(10, Settings::instance()->get_string_array(conf_key_substitution_patterns)),
194
  entry_substitution_completion_ (Gtk::EntryCompletion::create()),
195 196
  button_multiple_        (0),
  button_caseless_        (0),
197 198
  filetree_               (Gtk::manage(new FileTree())),
  scrollwin_filetree_     (0),
199
  scrollwin_textview_     (0),
200
  textview_               (Gtk::manage(new Gsv::View())),
201
  entry_preview_          (0),
202
  statusline_             (Gtk::manage(new StatusLine())),
203 204 205
  busy_action_running_    (false),
  busy_action_cancel_     (false),
  busy_action_iteration_  (0),
206 207 208 209
  undo_stack_             (new UndoStack()),
  match_action_group_     (Gio::SimpleActionGroup::create()),
  edit_action_group_      (Gio::SimpleActionGroup::create()),
  save_action_group_      (Gio::SimpleActionGroup::create())
daniel_e's avatar
daniel_e committed
210
{
211
  load_xml();
212

213 214
  entry_regex_ = comboboxentry_regex_->get_entry();
  entry_substitution_ = comboboxentry_substitution_->get_entry();
215

216
  textview_->set_buffer(FileBuffer::create());
217
  window_->set_title(PACKAGE_NAME);
218 219
  headerbar_->set_title(PACKAGE_NAME);
  headerbar_->set_show_close_button(true);
daniel_e's avatar
daniel_e committed
220

221 222
  vbox_main_->pack_start(*statusline_, Gtk::PACK_SHRINK);
  scrollwin_filetree_->add(*filetree_);
223
  grid_file_->attach(*combo_entry_pattern_, 1, 1, 1, 1);
224

225
  scrollwin_textview_->add(*textview_);
226

227
  headerbar_->show_all();
228 229 230
  statusline_->show_all();
  filetree_->show_all();
  combo_entry_pattern_->show_all();
231
  scrollwin_textview_->show_all();
232

233
  connect_signals();
daniel_e's avatar
daniel_e committed
234 235 236 237 238
}

MainWindow::~MainWindow()
{}

Fabien Parent's avatar
Fabien Parent committed
239 240
void MainWindow::initialize(const Glib::RefPtr<Gtk::Application>& application,
                            const InitState& init)
241
{
242 243 244 245 246 247 248 249 250
  Glib::RefPtr<Gio::Settings> settings = Settings::instance();
  int width = settings->get_int(conf_key_window_width);
  int height = settings->get_int(conf_key_window_height);

  int x = settings->get_int(conf_key_window_position_x);
  int y = settings->get_int(conf_key_window_position_y);

  bool maximized = settings->get_boolean(conf_key_window_maximized);

Fabien Parent's avatar
Fabien Parent committed
251 252 253 254 255 256
  application_ = application;
  application->signal_startup().connect
      (sigc::mem_fun(*this, &MainWindow::on_startup));
  application->register_application();

  window_->set_application(application_);
257 258 259 260 261
  window_->resize(width, height);
  window_->move(x, y);
  if (maximized)
    window_->maximize();

262 263 264 265 266 267 268 269 270 271 272 273 274
  init_actions();
  set_sensitive(match_action_group_, false);
  set_sensitive(edit_action_group_, false);
  set_sensitive(save_action_group_, true);
  set_sensitive("save", false);
  set_sensitive("save-all", false);

  Glib::RefPtr<Gtk::Builder> builder =
      Gtk::Builder::create_from_file(ui_gearmenu_filename);
  Glib::RefPtr<Gio::MenuModel> gearmenu =
    Glib::RefPtr<Gio::MenuModel>::cast_static(builder->get_object("gearmenu"));
  button_gear_->set_menu_model(gearmenu);

275 276 277
  textview_->set_show_line_numbers(settings->get_boolean(conf_key_show_line_numbers));
  textview_->set_highlight_current_line(settings->get_boolean(conf_key_highlight_current_line));
  textview_->set_auto_indent(settings->get_boolean(conf_key_auto_indentation));
278
  textview_->set_draw_spaces(static_cast<Gsv::DrawSpacesFlags>
279 280
                              (settings->get_flags(conf_key_draw_spaces)));

281 282
  std::string folder;

283 284
  if (!init.folder.empty())
    folder = init.folder.front();
285 286 287 288
  if (!Glib::path_is_absolute(folder))
    folder = Glib::build_filename(Glib::get_current_dir(), folder);

  const bool folder_exists = button_folder_->set_current_folder(folder);
289

290
  combo_entry_pattern_->get_entry()->set_text((init.pattern.empty()) ? Glib::ustring(1, '*') : init.pattern);
291

292 293
  entry_regex_->set_text(init.regex);
  entry_regex_->set_completion(entry_regex_completion_);
294
  entry_substitution_->set_text(init.substitution);
295 296 297
  entry_substitution_->set_completion(entry_substitution_completion_);

  comboboxentry_regex_->set_model(entry_regex_completion_stack_.get_completion_model());
298
  comboboxentry_regex_->set_entry_text_column(entry_regex_completion_stack_.get_completion_column());
299
  comboboxentry_substitution_->set_model(entry_substitution_completion_stack_.get_completion_model());
300
  comboboxentry_substitution_->set_entry_text_column(entry_substitution_completion_stack_.get_completion_column());
301

302 303 304 305
  entry_regex_completion_->set_model(entry_regex_completion_stack_.get_completion_model());
  entry_regex_completion_->set_text_column(entry_regex_completion_stack_.get_completion_column());
  entry_regex_completion_->set_inline_completion(true);
  entry_regex_completion_->set_popup_completion(false);
306

307 308 309 310
  entry_substitution_completion_->set_model(entry_substitution_completion_stack_.get_completion_model());
  entry_substitution_completion_->set_text_column(entry_substitution_completion_stack_.get_completion_column());
  entry_substitution_completion_->set_inline_completion(true);
  entry_substitution_completion_->set_popup_completion(false);
311

312 313 314 315
  button_recursive_->set_active(!init.no_recursive);
  button_hidden_   ->set_active(init.hidden);
  button_multiple_ ->set_active(!init.no_global);
  button_caseless_ ->set_active(init.ignorecase);
316

317
  combo_entry_pattern_->set_entry_text_column(0);
318 319 320 321 322 323
  const std::list<Glib::ustring> patterns =
      settings->get_string_array(conf_key_files_patterns);
  for (std::list<Glib::ustring>::const_iterator pattern = patterns.begin();
       pattern != patterns.end();
       ++pattern)
  {
324
    combo_entry_pattern_->append(*pattern);
325
  }
326

327
  if (init.feedback)
328 329
    filetree_->signal_feedback.connect(&print_location);

330 331 332 333
  // Strangely, folder_exists seems to be always true, probably because the
  // file chooser works asynchronously but the GLib main loop isn't running
  // yet.  As a work-around, explicitely check whether the directory exists
  // on the file system as well.
334 335
  if (folder_exists && !init.no_autorun
      && !init.folder.empty() && !init.pattern.empty()
336 337
      && Glib::file_test(folder, Glib::FILE_TEST_IS_DIR))
  {
338
    Glib::signal_idle().connect(sigc::mem_fun(*this, &MainWindow::autorun_idle));
339
  }
340 341
}

342 343
/**** Regexxer::MainWindow -- private **************************************/

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
void MainWindow::set_sensitive(const Glib::RefPtr<Gio::SimpleActionGroup>& group,
                               bool sensitive)
{
  std::vector<Glib::ustring> actions = group->list_actions();
  for (std::vector<Glib::ustring>::iterator i = actions.begin();
       i != actions.end();
       ++i)
  {
    Glib::RefPtr<Gio::SimpleAction> action =
        Glib::RefPtr<Gio::SimpleAction>::cast_static(group->lookup_action(*i));
    if (!action_enabled_.count(*i))
        action_enabled_[*i] = true;
    action->set_enabled(action_enabled_[*i] && sensitive);
  }

  action_group_enabled_[group] = sensitive;
}

void MainWindow::set_sensitive(const Glib::ustring& action_name, bool sensitive)
{
  Glib::RefPtr<Gio::SimpleActionGroup> group = action_to_group_[action_name];
  Glib::RefPtr<Gio::SimpleAction> action =
      Glib::RefPtr<Gio::SimpleAction>::cast_static
          (group->lookup_action(action_name));

  action->set_enabled(action_group_enabled_[group] && sensitive);
  action_enabled_[action_name] = sensitive;
}

Fabien Parent's avatar
Fabien Parent committed
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
void MainWindow::on_startup()
{
  static struct
  {
    const char* const name;
    sigc::slot<void> slot;
  } appmenu_actions[] =
  {
    {"preferences", sigc::mem_fun(*this, &MainWindow::on_preferences)},
    {"about", sigc::mem_fun(*this, &MainWindow::on_about)},
    {"quit", sigc::mem_fun(*this, &MainWindow::on_quit)},
    {0},
  };

  Glib::RefPtr<Gtk::Builder> builder =
      Gtk::Builder::create_from_file(ui_appmenu_filename);

  for (int i = 0; appmenu_actions[i].name; i++)
  {
    Glib::RefPtr<Gio::SimpleAction> action =
        Gio::SimpleAction::create(appmenu_actions[i].name);
    application_->add_action(action);
    action->signal_activate().connect(sigc::hide(appmenu_actions[i].slot));
  }

  Glib::RefPtr<Gio::MenuModel> appmenu =
      Glib::RefPtr<Gio::MenuModel>::cast_static(builder->get_object("appmenu"));
  application_->set_app_menu(appmenu);
}

403 404 405 406 407
void MainWindow::init_actions()
{
  struct actions
  {
    const char *const name;
408
    const char* accelerator;
409 410 411 412 413
    sigc::slot<void> slot;
  };

  static struct actions match_actions[] =
  {
414 415 416 417 418 419 420 421
    {"undo", "<Ctrl>Z", sigc::mem_fun(*this, &MainWindow::on_undo)},
    {"previous-file", "<Ctrl>P",sigc::bind(sigc::mem_fun(*this, &MainWindow::on_go_next_file), false)},
    {"back", "<Ctrl>B", sigc::bind(sigc::mem_fun(*this, &MainWindow::on_go_next), false)},
    {"forward", "<Ctrl>N", sigc::bind(sigc::mem_fun(*this, &MainWindow::on_go_next), true)},
    {"next-file", "<Ctrl>E", sigc::bind(sigc::mem_fun(*this, &MainWindow::on_go_next_file), true)},
    {"replace-current", "<Ctrl>R", sigc::mem_fun(*this, &MainWindow::on_replace)},
    {"replace-in-file", NULL, sigc::mem_fun(*this, &MainWindow::on_replace_file)},
    {"replace-in-all-files", NULL, sigc::mem_fun(*this, &MainWindow::on_replace_all)},
422 423 424 425 426 427 428 429 430 431
    {0},
  };

  for (int i = 0; match_actions[i].name; i++)
  {
    Glib::RefPtr<Gio::SimpleAction> action =
        Gio::SimpleAction::create(match_actions[i].name);
    action->signal_activate().connect(sigc::hide(match_actions[i].slot));
    match_action_group_->insert(action);
    action_to_group_[match_actions[i].name] = match_action_group_;
432 433 434
    if (match_actions[i].accelerator)
        application_->add_accelerator(match_actions[i].accelerator,
                                      Glib::ustring("match.") + match_actions[i].name);
435 436 437 438
  }

  static struct actions edit_actions[] =
  {
439 440 441 442
    {"cut", "<Ctrl>X", sigc::mem_fun(*this, &MainWindow::on_cut)},
    {"copy", "<Ctrl>C", sigc::mem_fun(*this, &MainWindow::on_copy)},
    {"paste", "<Ctrl>V", sigc::mem_fun(*this, &MainWindow::on_paste)},
    {"delete", NULL, sigc::mem_fun(*this, &MainWindow::on_erase)},
443
    {0},
444 445 446 447 448 449 450 451 452
  };

  for (int i = 0; edit_actions[i].name; i++)
  {
    Glib::RefPtr<Gio::SimpleAction> action =
        Gio::SimpleAction::create(edit_actions[i].name);
    action->signal_activate().connect(sigc::hide(edit_actions[i].slot));
    edit_action_group_->insert(action);
    action_to_group_[edit_actions[i].name] = edit_action_group_;
453 454 455
    if (edit_actions[i].accelerator)
        application_->add_accelerator(edit_actions[i].accelerator,
                                      Glib::ustring("edit.") + edit_actions[i].name);
456 457 458 459
  }

  static struct actions save_actions[] =
  {
460 461
    {"save", "<Ctrl>S", sigc::mem_fun(*this, &MainWindow::on_save_file)},
    {"save-all", NULL, sigc::mem_fun(*this, &MainWindow::on_save_all)},
462
    {0},
463 464 465 466 467 468 469 470 471
  };

  for (int i = 0; save_actions[i].name; i++)
  {
    Glib::RefPtr<Gio::SimpleAction> action =
        Gio::SimpleAction::create(save_actions[i].name);
    action->signal_activate().connect(sigc::hide(save_actions[i].slot));
    save_action_group_->insert(action);
    action_to_group_[save_actions[i].name] = save_action_group_;
472 473 474
    if (save_actions[i].accelerator)
        application_->add_accelerator(save_actions[i].accelerator,
                                      Glib::ustring("save.") + save_actions[i].name);
475 476 477 478 479 480 481 482 483 484
  }

  window_->insert_action_group("match", match_action_group_);
  window_->insert_action_group("edit", edit_action_group_);
  window_->insert_action_group("save", save_action_group_);

//  controller_.find_files  .connect(mem_fun(*this, &MainWindow::on_find_files));
//  controller_.find_matches.connect(mem_fun(*this, &MainWindow::on_exec_search));
}

485
void MainWindow::load_xml()
486
{
487
  const Glib::RefPtr<Gtk::Builder> xml = Gtk::Builder::create_from_file(ui_mainwindow_filename);
488

Fabien Parent's avatar
Fabien Parent committed
489
  Gtk::ApplicationWindow* mainwindow = 0;
490 491
  xml->get_widget("mainwindow", mainwindow);
  window_.reset(mainwindow);
492

493 494
  xml->get_widget("headerbar",           headerbar_);
  xml->get_widget("button_gear",         button_gear_);
495
  xml->get_widget("button_folder",       button_folder_);
496 497
  xml->get_widget("button_recursive",    button_recursive_);
  xml->get_widget("button_hidden",       button_hidden_);
498 499
  xml->get_widget("comboboxentry_regex",         comboboxentry_regex_);
  xml->get_widget("comboboxentry_substitution",  comboboxentry_substitution_);
500 501
  xml->get_widget("button_multiple",     button_multiple_);
  xml->get_widget("button_caseless",     button_caseless_);
502
  xml->get_widget("scrollwin_textview",  scrollwin_textview_);
503
  xml->get_widget("entry_preview",       entry_preview_);
504 505
  xml->get_widget("vbox_main",           vbox_main_);
  xml->get_widget("scrollwin_filetree",  scrollwin_filetree_);
506
  xml->get_widget("grid_file",           grid_file_);
507

508
  controller_.load_xml(xml);
509 510
}

511
void MainWindow::connect_signals()
daniel_e's avatar
daniel_e committed
512
{
513 514
  using sigc::bind;
  using sigc::mem_fun;
daniel_e's avatar
daniel_e committed
515

516
  window_->signal_hide         ().connect(mem_fun(*this, &MainWindow::on_hide));
517
  window_->signal_style_updated().connect(mem_fun(*this, &MainWindow::on_style_updated));
518
  window_->signal_delete_event ().connect(mem_fun(*this, &MainWindow::on_delete_event));
daniel_e's avatar
daniel_e committed
519

520 521
  combo_entry_pattern_->get_entry()->signal_activate().connect(controller_.find_files.slot());
  combo_entry_pattern_->signal_changed ().connect(mem_fun(*this, &MainWindow::on_entry_pattern_changed));
daniel_e's avatar
daniel_e committed
522

523 524 525 526 527 528 529
  entry_regex_       ->signal_activate().connect(controller_.find_matches.slot());
  entry_substitution_->signal_activate().connect(controller_.find_matches.slot());
  entry_substitution_->signal_changed ().connect(mem_fun(*this, &MainWindow::update_preview));

  controller_.find_files  .connect(mem_fun(*this, &MainWindow::on_find_files));
  controller_.find_matches.connect(mem_fun(*this, &MainWindow::on_exec_search));

530
  Settings::instance()->signal_changed().connect(mem_fun(*this, &MainWindow::on_conf_value_changed));
531 532 533

  statusline_->signal_cancel_clicked.connect(
      mem_fun(*this, &MainWindow::on_busy_action_cancel));
534

535 536
  filetree_->signal_switch_buffer.connect(
      mem_fun(*this, &MainWindow::on_filetree_switch_buffer));
daniel_e's avatar
daniel_e committed
537

538 539
  filetree_->signal_bound_state_changed.connect(
      mem_fun(*this, &MainWindow::on_bound_state_changed));
daniel_e's avatar
daniel_e committed
540

541 542
  filetree_->signal_file_count_changed.connect(
      mem_fun(*this, &MainWindow::on_filetree_file_count_changed));
daniel_e's avatar
daniel_e committed
543

544 545
  filetree_->signal_match_count_changed.connect(
      mem_fun(*this, &MainWindow::on_filetree_match_count_changed));
daniel_e's avatar
daniel_e committed
546

547 548
  filetree_->signal_modified_count_changed.connect(
      mem_fun(*this, &MainWindow::on_filetree_modified_count_changed));
549

550 551
  filetree_->signal_pulse.connect(
      mem_fun(*this, &MainWindow::on_busy_action_pulse));
daniel_e's avatar
daniel_e committed
552

553 554
  filetree_->signal_undo_stack_push.connect(
      mem_fun(*this, &MainWindow::on_undo_stack_push));
daniel_e's avatar
daniel_e committed
555 556
}

557 558 559 560 561 562 563 564 565 566
bool MainWindow::autorun_idle()
{
  controller_.find_files.activate();

  if (!busy_action_cancel_ && entry_regex_->get_text_length() > 0)
    controller_.find_matches.activate();

  return false;
}

567
void MainWindow::on_hide()
daniel_e's avatar
daniel_e committed
568
{
569
  on_busy_action_cancel();
daniel_e's avatar
daniel_e committed
570

571 572 573 574
  // Kill the dialogs if they're mapped right now.  This isn't strictly
  // necessary since they'd be deleted in the destructor anyway.  But if we
  // have to do a lot of cleanup the dialogs would stay open for that time,
  // which doesn't look neat.
575 576
  about_dialog_.reset();
  pref_dialog_.reset();
577
}
578

579
void MainWindow::on_style_updated()
580 581 582
{
  FileBuffer::pango_context_changed(window_->get_pango_context());
}
daniel_e's avatar
daniel_e committed
583

584 585
bool MainWindow::on_delete_event(GdkEventAny*)
{
586 587 588
  bool quit = confirm_quit_request();
  save_window_state();
  return !quit;
daniel_e's avatar
daniel_e committed
589 590
}

591 592
void MainWindow::on_cut()
{
593 594 595 596 597 598 599 600 601
  if (textview_->is_focus())
  {
    if (const Glib::RefPtr<Gtk::TextBuffer> buffer = textview_->get_buffer())
      buffer->cut_clipboard(textview_->get_clipboard(selection_clipboard),
                            textview_->get_editable());
  }
  else
  {
    const int noEntries = 3;
602
    Gtk::Entry *entries[noEntries] = { combo_entry_pattern_->get_entry(), entry_regex_,
603 604 605 606 607 608 609 610 611 612
                                       entry_substitution_ };
    for (int i = 0; i < 3; i++)
    {
      if (entries[i]->is_focus())
      {
        ((Gtk::Editable *)entries[i])->cut_clipboard();
        return ;
      }
    }
  }
613 614 615 616
}

void MainWindow::on_copy()
{
617 618 619 620 621 622 623 624
  if (textview_->is_focus())
  {
    if (const Glib::RefPtr<Gtk::TextBuffer> buffer = textview_->get_buffer())
      buffer->copy_clipboard(textview_->get_clipboard(selection_clipboard));
  }
  else
  {
    const int noEntries = 3;
625
    Gtk::Entry *entries[noEntries] = { combo_entry_pattern_->get_entry(), entry_regex_,
626 627 628 629 630 631 632 633 634 635
                                       entry_substitution_ };
    for (int i = 0; i < 3; i++)
    {
      if (entries[i]->is_focus())
      {
        ((Gtk::Editable *)entries[i])->copy_clipboard();
        return ;
      }
    }
  }
636 637 638 639
}

void MainWindow::on_paste()
{
640 641 642 643 644 645 646 647 648
  if (textview_->is_focus())
  {
    if (const Glib::RefPtr<Gtk::TextBuffer> buffer = textview_->get_buffer())
      buffer->paste_clipboard(textview_->get_clipboard(selection_clipboard),
                              textview_->get_editable());
  }
  else
  {
    const int noEntries = 3;
649
    Gtk::Entry *entries[noEntries] = { combo_entry_pattern_->get_entry(), entry_regex_,
650 651 652 653 654 655 656 657 658 659
                                       entry_substitution_ };
    for (int i = 0; i < 3; i++)
    {
      if (entries[i]->is_focus())
      {
        ((Gtk::Editable *)entries[i])->paste_clipboard();
        return ;
      }
    }
  }
660 661 662 663 664 665 666 667
}

void MainWindow::on_erase()
{
  if (const Glib::RefPtr<Gtk::TextBuffer> buffer = textview_->get_buffer())
    buffer->erase_selection(true, textview_->get_editable());
}

668 669
void MainWindow::on_quit()
{
670
  if (confirm_quit_request())
671 672
  {
    save_window_state();
673
    window_->hide();
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  }
}

void MainWindow::save_window_state()
{
  int x = 0;
  int y = 0;

  int width = 0;
  int height = 0;

  window_->get_position(x, y);
  window_->get_size(width, height);
  bool maximized = (window_->get_window()->get_state() & Gdk::WINDOW_STATE_MAXIMIZED);

  Glib::RefPtr<Gio::Settings> settings = Settings::instance();

  settings->set_int(conf_key_window_position_x, x);
  settings->set_int(conf_key_window_position_y, y);
  settings->set_boolean(conf_key_window_maximized, maximized);

  if (!maximized)
  {
    settings->set_int(conf_key_window_width, width);
    settings->set_int(conf_key_window_height, height);
  }
700 701 702 703
}

bool MainWindow::confirm_quit_request()
{
704
  if (filetree_->get_modified_count() == 0)
705 706
    return true;

707 708
  Gtk::MessageDialog dialog (*window_,
                             _("Some files haven\342\200\231t been saved yet.\nQuit anyway?"),
709
                             false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE, true);
710

711 712
  dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
  dialog.add_button(_("_Quit"), Gtk::RESPONSE_OK);
713 714 715 716

  return (dialog.run() == Gtk::RESPONSE_OK);
}

daniel_e's avatar
daniel_e committed
717 718
void MainWindow::on_find_files()
{
719
  if (filetree_->get_modified_count() > 0)
720
  {
721 722
    Gtk::MessageDialog dialog (*window_,
                               _("Some files haven\342\200\231t been saved yet.\nContinue anyway?"),
723
                               false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_OK_CANCEL, true);
724

725
    if (dialog.run() != Gtk::RESPONSE_OK)
726 727 728
      return;
  }

729
  std::string folder = button_folder_->get_filename();
730

731
  if (folder.empty())
732 733 734
    folder = Glib::get_current_dir();

  g_return_if_fail(Glib::path_is_absolute(folder));
735 736

  undo_stack_clear();
737

738 739
  BusyAction busy (*this);

740 741
  try
  {
742 743 744
    Glib::RefPtr<Glib::Regex> pattern = Glib::Regex::create(
        Util::shell_pattern_to_regex(combo_entry_pattern_->get_entry()->get_text()),
        Glib::REGEX_DOTALL);
745

746 747 748
    filetree_->find_files(folder, pattern,
                          button_recursive_->get_active(),
                          button_hidden_->get_active());
749
  }
750
  catch (const Glib::RegexError&)
751
  {
752 753
    Gtk::MessageDialog dialog (*window_, _("The file search pattern is invalid."),
                               false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
754 755
    dialog.run();
  }
756
  catch (const FileTree::Error& error)
757
  {
758 759
    FileErrorDialog dialog (*window_, _("The following errors occurred during search:"),
                            Gtk::MESSAGE_WARNING, error);
760 761
    dialog.run();
  }
762

763
  statusline_->set_file_count(filetree_->get_file_count());
daniel_e's avatar
daniel_e committed
764 765 766 767
}

void MainWindow::on_exec_search()
{
768 769
  BusyAction busy (*this);

770 771 772
  const Glib::ustring regex = entry_regex_->get_text();
  const bool caseless = button_caseless_->get_active();
  const bool multiple = button_multiple_->get_active();
773

774
  entry_regex_completion_stack_.push(regex);
775 776 777

  Settings::instance()->set_string_array(conf_key_regex_patterns, entry_regex_completion_stack_.get_stack());

daniel_e's avatar
daniel_e committed
778 779
  try
  {
780 781 782
    Glib::RefPtr<Glib::Regex> pattern =
        Glib::Regex::create(regex, (caseless) ? Glib::REGEX_CASELESS
                                              : static_cast<Glib::RegexCompileFlags>(0));
783

784
    filetree_->find_matches(pattern, multiple);
daniel_e's avatar
daniel_e committed
785
  }
786
  catch (const Glib::RegexError& error)
daniel_e's avatar
daniel_e committed
787
  {
788 789
    Gtk::MessageDialog dialog (*window_, error.what(), false,
                               Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
790 791
    dialog.run();

daniel_e's avatar
daniel_e committed
792 793 794
    return;
  }

795
  if (const FileBufferPtr buffer = FileBufferPtr::cast_static(textview_->get_buffer()))
796 797 798 799 800
  {
    statusline_->set_match_count(buffer->get_original_match_count());
    statusline_->set_match_index(buffer->get_match_index());
  }

801
  if (filetree_->get_match_count() > 0)
daniel_e's avatar
daniel_e committed
802
  {
803 804 805 806
    // Scrolling has to be post-poned after the redraw, otherwise we might
    // not end up where we want to.  So do that by installing an idle handler.

    Glib::signal_idle().connect(
807
        sigc::mem_fun(*this, &MainWindow::after_exec_search),
808
        Glib::PRIORITY_HIGH_IDLE + 25); // slightly less than redraw (+20)
daniel_e's avatar
daniel_e committed
809 810 811
  }
}

812
bool MainWindow::after_exec_search()
813
{
814
  filetree_->select_first_file();
815
  on_go_next(true);
816

817
  return false;
818 819
}

820
void MainWindow::on_filetree_switch_buffer(FileInfoPtr fileinfo, int file_index)
daniel_e's avatar
daniel_e committed
821
{
822
  const FileBufferPtr old_buffer = FileBufferPtr::cast_static(textview_->get_buffer());
daniel_e's avatar
daniel_e committed
823

824
  if (fileinfo && fileinfo->buffer == old_buffer)
daniel_e's avatar
daniel_e committed
825 826
    return;

827
  if (old_buffer)
daniel_e's avatar
daniel_e committed
828
  {
829
    std::for_each(buffer_connections_.begin(), buffer_connections_.end(),
830
                  std::mem_fun_ref(&sigc::connection::disconnect));
daniel_e's avatar
daniel_e committed
831

832
    buffer_connections_.clear();
daniel_e's avatar
daniel_e committed
833 834 835
    old_buffer->forget_current_match();
  }

836
  if (fileinfo)
daniel_e's avatar
daniel_e committed
837
  {
838
    const FileBufferPtr buffer = fileinfo->buffer;
839
    g_return_if_fail(buffer);
840 841

    textview_->set_buffer(buffer);
842
    textview_->set_editable(!fileinfo->load_failed);
843
    textview_->set_cursor_visible(!fileinfo->load_failed);
844

845
    if (!fileinfo->load_failed)
846 847
    {
      buffer_connections_.push_back(buffer->signal_modified_changed().
848
          connect(sigc::mem_fun(*this, &MainWindow::on_buffer_modified_changed)));
849

850
      buffer_connections_.push_back(buffer->signal_bound_state_changed.
851
          connect(sigc::mem_fun(*this, &MainWindow::on_bound_state_changed)));
852

853
      buffer_connections_.push_back(buffer->signal_preview_line_changed.
854
          connect(sigc::mem_fun(*this, &MainWindow::update_preview)));
855
    }
daniel_e's avatar
daniel_e committed
856

857
    set_title_filename(fileinfo->fullname);
daniel_e's avatar
daniel_e committed
858

859 860 861
    set_sensitive("replace-in-file", buffer->get_match_count() > 0);
    set_sensitive("save", buffer->get_modified());
    set_sensitive(edit_action_group_, !fileinfo->load_failed);
862 863 864

    statusline_->set_match_count(buffer->get_original_match_count());
    statusline_->set_match_index(buffer->get_match_index());
865
    statusline_->set_file_encoding(fileinfo->encoding);
daniel_e's avatar
daniel_e committed
866 867 868 869
  }
  else
  {
    textview_->set_buffer(FileBuffer::create());
870
    textview_->set_editable(false);
871
    textview_->set_cursor_visible(false);
872

873
    window_->set_title(PACKAGE_NAME);
874 875
    headerbar_->set_title(PACKAGE_NAME);
    headerbar_->set_subtitle("");
daniel_e's avatar
daniel_e committed
876

877 878 879
    set_sensitive("replace-in-file", false);
    set_sensitive("save", false);
    set_sensitive(edit_action_group_, false);
880 881 882

    statusline_->set_match_count(0);
    statusline_->set_match_index(0);
883
    statusline_->set_file_encoding("");
daniel_e's avatar
daniel_e committed
884 885
  }

886
  statusline_->set_file_index(file_index);
daniel_e's avatar
daniel_e committed
887 888 889
  update_preview();
}

890
void MainWindow::on_bound_state_changed()
891
{