File: sec-buildapp-search-bar.html

package info (click to toggle)
gtkmm-documentation 4.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,772 kB
  • sloc: cpp: 15,541; javascript: 1,208; makefile: 1,080; python: 401; xml: 106; perl: 67; sh: 8
file content (383 lines) | stat: -rw-r--r-- 14,515 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="highlight.min.css">
<script src="highlight.min.js"></script><script>
      hljs.configure({languages: ['cpp']});
      hljs.highlightAll();
    </script><title>Adding a search bar</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot">
<link rel="home" href="index.html" title="Programming with gtkmm 4">
<link rel="up" href="chapter-building-applications.html" title="Chapter 31. Building applications">
<link rel="prev" href="sec-buildapp-pref-dialog.html" title="A preference dialog">
<link rel="next" href="sec-buildapp-side-bar.html" title="Adding a side bar">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">Adding a search bar</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="sec-buildapp-pref-dialog.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<th width="60%" align="center">Chapter 31. Building applications</th>
<td width="20%" align="right"> <a accesskey="n" href="sec-buildapp-side-bar.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
</table>
<hr>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="sec-buildapp-search-bar"></a>Adding a search bar</h2></div></div></div>


<p>
We continue to flesh out the functionality of our application. For now, we add search.
<span class="application">gtkmm</span> supports this with <code class="classname">Gtk::SearchEntry</code> and <code class="classname">Gtk::SearchBar</code>.
The search bar is a widget that can slide in from the top to present a search entry.
</p>

<p>
We add a toggle button to the header bar, which can be used to slide out the search bar
below the header bar. The new widgets are added in the <code class="filename">window.ui</code> file.
</p>

<p>
Implementing the search needs quite a few code changes that we are not going to completely
go over here. The central piece of the search implementation is a signal handler that
listens for text changes in the search entry, shown here without error handling.
</p>
<pre class="programlisting"><code class="code">void ExampleAppWindow::on_search_text_changed()
{
  const auto text = m_searchentry-&gt;get_text();
  auto tab = dynamic_cast&lt;Gtk::ScrolledWindow*&gt;(m_stack-&gt;get_visible_child());
  auto view = dynamic_cast&lt;Gtk::TextView*&gt;(tab-&gt;get_child());

  // Very simple-minded search implementation.
  auto buffer = view-&gt;get_buffer();
  Gtk::TextIter match_start;
  Gtk::TextIter match_end;
  if (buffer-&gt;begin().forward_search(text, Gtk::TextSearchFlags::CASE_INSENSITIVE,
      match_start, match_end))
  {
    buffer-&gt;select_range(match_start, match_end);
    view-&gt;scroll_to(match_start);
  }
}
</code></pre>

<p>
With the search bar, our application now looks like this:
</p>

<div class="figure">
<a name="figure-buildapp-search-bar"></a><p class="title"><b>Figure 31.6. Adding a search bar</b></p>
<div class="figure-contents">
  
  <div class="screenshot">
    <div class="mediaobject"><img src="figures/buildapp_search_bar.png" alt="Adding a search bar"></div>
  </div>
</div>
</div>
<br class="figure-break">

<p><a class="ulink" href="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step6" target="_top">Source Code</a></p>

<p>File: <code class="filename">exampleapplication.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "../step4/exampleapplication.h"
// Equal to the corresponding file in step4
</code></pre>
<p>File: <code class="filename">exampleappprefs.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "../step5/exampleappprefs.h"
// Equal to the corresponding file in step5
</code></pre>
<p>File: <code class="filename">exampleappwindow.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_EXAMPLEAPPWINDOW_H_
#define GTKMM_EXAMPLEAPPWINDOW_H_

#include &lt;gtkmm.h&gt;

#define HAS_SEARCH_ENTRY2 GTKMM_CHECK_VERSION(4,13,2)

class ExampleAppWindow : public Gtk::ApplicationWindow
{
public:
  ExampleAppWindow(BaseObjectType* cobject,
    const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; refBuilder);

  static ExampleAppWindow* create();

  void open_file_view(const Glib::RefPtr&lt;Gio::File&gt;&amp; file);

protected:
  // Signal handlers
  void on_search_text_changed();
  void on_visible_child_changed();

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;
  Glib::RefPtr&lt;Gio::Settings&gt; m_settings;
  Gtk::Stack* m_stack {nullptr};
  Gtk::ToggleButton* m_search {nullptr};
  Gtk::SearchBar* m_searchbar {nullptr};
#if HAS_SEARCH_ENTRY2
  Gtk::SearchEntry2* m_searchentry {nullptr};
#else
  Gtk::SearchEntry* m_searchentry {nullptr};
#endif
  Gtk::MenuButton* m_gears {nullptr};
  Glib::RefPtr&lt;Glib::Binding&gt; m_prop_binding;
};

#endif /* GTKMM_EXAMPLEAPPWINDOW_H */
</code></pre>
<p>File: <code class="filename">exampleapplication.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "../step5/exampleapplication.cc"
// Equal to the corresponding file in step5
</code></pre>
<p>File: <code class="filename">exampleappprefs.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "../step5/exampleappprefs.cc"
// Equal to the corresponding file in step5
</code></pre>
<p>File: <code class="filename">exampleappwindow.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "exampleappwindow.h"
#include &lt;iostream&gt;
#include &lt;stdexcept&gt;

ExampleAppWindow::ExampleAppWindow(BaseObjectType* cobject,
  const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; refBuilder)
: Gtk::ApplicationWindow(cobject),
  m_refBuilder(refBuilder)
{
  // Get widgets from the Gtk::Builder file.
  m_stack = m_refBuilder-&gt;get_widget&lt;Gtk::Stack&gt;("stack");
  if (!m_stack)
    throw std::runtime_error("No \"stack\" object in window.ui");

  m_search = m_refBuilder-&gt;get_widget&lt;Gtk::ToggleButton&gt;("search");
  if (!m_search)
    throw std::runtime_error("No \"search\" object in window.ui");

  m_searchbar = m_refBuilder-&gt;get_widget&lt;Gtk::SearchBar&gt;("searchbar");
  if (!m_searchbar)
    throw std::runtime_error("No \"searchbar\" object in window.ui");

#if HAS_SEARCH_ENTRY2
  m_searchentry = m_refBuilder-&gt;get_widget&lt;Gtk::SearchEntry2&gt;("searchentry");
#else
  m_searchentry = m_refBuilder-&gt;get_widget&lt;Gtk::SearchEntry&gt;("searchentry");
#endif
  if (!m_searchentry)
    throw std::runtime_error("No \"searchentry\" object in window.ui");

  m_gears = m_refBuilder-&gt;get_widget&lt;Gtk::MenuButton&gt;("gears");
  if (!m_gears)
    throw std::runtime_error("No \"gears\" object in window.ui");

  // Bind settings.
  m_settings = Gio::Settings::create("org.gtkmm.exampleapp");
  m_settings-&gt;bind("transition", m_stack-&gt;property_transition_type());

  // Bind properties.
  m_prop_binding = Glib::Binding::bind_property(m_search-&gt;property_active(),
    m_searchbar-&gt;property_search_mode_enabled(), Glib::Binding::Flags::BIDIRECTIONAL);

  // Connect signal handlers.
  m_searchentry-&gt;signal_search_changed().connect(
    sigc::mem_fun(*this, &amp;ExampleAppWindow::on_search_text_changed));
  m_stack-&gt;property_visible_child().signal_changed().connect(
    sigc::mem_fun(*this, &amp;ExampleAppWindow::on_visible_child_changed));

  // Connect the menu to the MenuButton m_gears.
  // (The connection between action and menu item is specified in gears_menu.ui.)
  auto menu_builder = Gtk::Builder::create_from_resource("/org/gtkmm/exampleapp/gears_menu.ui");
  auto menu = menu_builder-&gt;get_object&lt;Gio::MenuModel&gt;("menu");
  if (!menu)
    throw std::runtime_error("No \"menu\" object in gears_menu.ui");

  m_gears-&gt;set_menu_model(menu);
}

//static
ExampleAppWindow* ExampleAppWindow::create()
{
  // Load the Builder file and instantiate its widgets.
  auto refBuilder = Gtk::Builder::create_from_resource("/org/gtkmm/exampleapp/window.ui");

  auto window = Gtk::Builder::get_widget_derived&lt;ExampleAppWindow&gt;(refBuilder, "app_window");
  if (!window)
    throw std::runtime_error("No \"app_window\" object in window.ui");

  return window;
}

void ExampleAppWindow::open_file_view(const Glib::RefPtr&lt;Gio::File&gt;&amp; file)
{
  const Glib::ustring basename = file-&gt;get_basename();

  auto scrolled = Gtk::make_managed&lt;Gtk::ScrolledWindow&gt;();
  scrolled-&gt;set_expand(true);
  auto view = Gtk::make_managed&lt;Gtk::TextView&gt;();
  view-&gt;set_editable(false);
  view-&gt;set_cursor_visible(false);
  scrolled-&gt;set_child(*view);
  m_stack-&gt;add(*scrolled, basename, basename);

  auto buffer = view-&gt;get_buffer();
  try
  {
    char* contents = nullptr;
    gsize length = 0;
    
    file-&gt;load_contents(contents, length);
    buffer-&gt;set_text(contents, contents+length);
    g_free(contents);
  }
  catch (const Glib::Error&amp; ex)
  {
    std::cout &lt;&lt; "ExampleAppWindow::open_file_view(\"" &lt;&lt; file-&gt;get_parse_name()
      &lt;&lt; "\"):\n  " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return;
  }

  auto tag = buffer-&gt;create_tag();
  m_settings-&gt;bind("font", tag-&gt;property_font());
  buffer-&gt;apply_tag(tag, buffer-&gt;begin(), buffer-&gt;end());

  m_search-&gt;set_sensitive(true);
}

void ExampleAppWindow::on_search_text_changed()
{
  const auto text = m_searchentry-&gt;get_text();
  if (text.empty())
    return;

  auto tab = dynamic_cast&lt;Gtk::ScrolledWindow*&gt;(m_stack-&gt;get_visible_child());
  if (!tab)
  {
    std::cout &lt;&lt; "ExampleAppWindow::on_search_text_changed(): No visible child." &lt;&lt; std::endl;
    return;
  }

  auto view = dynamic_cast&lt;Gtk::TextView*&gt;(tab-&gt;get_child());
  if (!view)
  {
    std::cout &lt;&lt; "ExampleAppWindow::on_search_text_changed(): No visible text view." &lt;&lt; std::endl;
    return;
  }

  // Very simple-minded search implementation.
  auto buffer = view-&gt;get_buffer();
  Gtk::TextIter match_start;
  Gtk::TextIter match_end;
  if (buffer-&gt;begin().forward_search(text, Gtk::TextSearchFlags::CASE_INSENSITIVE,
      match_start, match_end))
  {
    buffer-&gt;select_range(match_start, match_end);
    view-&gt;scroll_to(match_start);
  }
}

void ExampleAppWindow::on_visible_child_changed()
{
  m_searchbar-&gt;set_search_mode(false);
}

</code></pre>
<p>File: <code class="filename">main.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "exampleapplication.h"
#include "exampleappwindow.h"

int main(int argc, char* argv[])
{
#if HAS_SEARCH_ENTRY2
  // A GtkSearchEntry (e.g. from window.ui) shall be wrapped in
  // a Gtk::SearhcEntry2 and not in a deprecated Gtk::SearchEntry.
  Gtk::Application::wrap_in_search_entry2(true);
#endif

  // Since this example is running uninstalled, we have to help it find its
  // schema. This is *not* necessary in a properly installed application.
  Glib::setenv ("GSETTINGS_SCHEMA_DIR", ".", false);

  auto application = ExampleApplication::create();

  // Start the application, showing the initial window,
  // and opening extra views for any files that it is asked to open,
  // for instance as a command-line parameter.
  // run() will return when the last window has been closed.
  return application-&gt;run(argc, argv);
}
</code></pre>
<p>File: <code class="filename">window.ui</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;interface&gt;
  &lt;object class="GtkApplicationWindow" id="app_window"&gt;
    &lt;property name="title" translatable="yes"&gt;Example Application&lt;/property&gt;
    &lt;property name="default-width"&gt;600&lt;/property&gt;
    &lt;property name="default-height"&gt;400&lt;/property&gt;
    &lt;property name="hide-on-close"&gt;True&lt;/property&gt;
    &lt;child type="titlebar"&gt;
      &lt;object class="GtkHeaderBar" id="header"&gt;
        &lt;child type="title"&gt;
          &lt;object class="GtkStackSwitcher" id="tabs"&gt;
            &lt;property name="stack"&gt;stack&lt;/property&gt;
          &lt;/object&gt;
        &lt;/child&gt;
        &lt;child type="end"&gt;
          &lt;object class="GtkMenuButton" id="gears"&gt;
            &lt;property name="direction"&gt;none&lt;/property&gt;
          &lt;/object&gt;
        &lt;/child&gt;
        &lt;child type="end"&gt;
          &lt;object class="GtkToggleButton" id="search"&gt;
            &lt;property name="sensitive"&gt;False&lt;/property&gt;
            &lt;property name="icon-name"&gt;edit-find-symbolic&lt;/property&gt;
          &lt;/object&gt;
        &lt;/child&gt;
      &lt;/object&gt;
    &lt;/child&gt;
    &lt;child&gt;
      &lt;object class="GtkBox" id="content_box"&gt;
        &lt;property name="orientation"&gt;vertical&lt;/property&gt;
        &lt;child&gt;
          &lt;object class="GtkSearchBar" id="searchbar"&gt;
            &lt;child&gt;
              &lt;object class="GtkSearchEntry" id="searchentry"&gt;
              &lt;/object&gt;
            &lt;/child&gt;
          &lt;/object&gt;
        &lt;/child&gt;
        &lt;child&gt;
          &lt;object class="GtkStack" id="stack"&gt;
            &lt;property name="transition-duration"&gt;500&lt;/property&gt;
          &lt;/object&gt;
        &lt;/child&gt;
      &lt;/object&gt;
    &lt;/child&gt;
  &lt;/object&gt;
&lt;/interface&gt;
</code></pre>


</div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="sec-buildapp-pref-dialog.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<td width="20%" align="center"><a accesskey="u" href="chapter-building-applications.html"><img src="icons/up.png" alt="Up"></a></td>
<td width="40%" align="right"> <a accesskey="n" href="sec-buildapp-side-bar.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">A preference dialog </td>
<td width="20%" align="center"><a accesskey="h" href="index.html"><img src="icons/home.png" alt="Home"></a></td>
<td width="40%" align="right" valign="top"> Adding a side bar</td>
</tr>
</table>
</div>
</body>
</html>