]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
6640b97e7b04b873fb8d9ece04b4df78f5e9aca8
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "texwindow.h"
29
30 #include <gtk/gtk.h>
31
32 #include "debugging/debugging.h"
33 #include "warnings.h"
34
35 #include "defaults.h"
36 #include "ifilesystem.h"
37 #include "iundo.h"
38 #include "igl.h"
39 #include "iarchive.h"
40 #include "moduleobserver.h"
41
42 #include <set>
43 #include <string>
44 #include <vector>
45
46 #include <uilib/uilib.h>
47
48 #include "signal/signal.h"
49 #include "math/vector.h"
50 #include "texturelib.h"
51 #include "string/string.h"
52 #include "shaderlib.h"
53 #include "os/file.h"
54 #include "os/path.h"
55 #include "stream/memstream.h"
56 #include "stream/textfilestream.h"
57 #include "stream/stringstream.h"
58 #include "cmdlib.h"
59 #include "texmanip.h"
60 #include "textures.h"
61 #include "convert.h"
62
63 #include "gtkutil/menu.h"
64 #include "gtkutil/nonmodal.h"
65 #include "gtkutil/cursor.h"
66 #include "gtkutil/widget.h"
67 #include "gtkutil/glwidget.h"
68 #include "gtkutil/messagebox.h"
69
70 #include "error.h"
71 #include "map.h"
72 #include "qgl.h"
73 #include "select.h"
74 #include "brush_primit.h"
75 #include "brushmanip.h"
76 #include "patchmanip.h"
77 #include "plugin.h"
78 #include "qe3.h"
79 #include "gtkdlgs.h"
80 #include "gtkmisc.h"
81 #include "mainframe.h"
82 #include "findtexturedialog.h"
83 #include "surfacedialog.h"
84 #include "patchdialog.h"
85 #include "groupdialog.h"
86 #include "preferences.h"
87 #include "shaders.h"
88 #include "commands.h"
89
90 bool TextureBrowser_showWads(){
91         return !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) );
92 }
93
94 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser );
95
96 bool string_equal_start( const char* string, StringRange start ){
97         return string_equal_n( string, start.first, start.last - start.first );
98 }
99
100 typedef std::set<CopiedString> TextureGroups;
101
102 void TextureGroups_addWad( TextureGroups& groups, const char* archive ){
103         if ( extension_equal( path_get_extension( archive ), "wad" ) ) {
104                 groups.insert( archive );
105         }
106 }
107
108 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addWad> TextureGroupsAddWadCaller;
109
110 namespace
111 {
112 bool g_TextureBrowser_shaderlistOnly = false;
113 bool g_TextureBrowser_fixedSize = true;
114 bool g_TextureBrowser_filterMissing = false;
115 bool g_TextureBrowser_filterFallback = true;
116 bool g_TextureBrowser_enableAlpha = true;
117 }
118
119 CopiedString g_notex;
120 CopiedString g_shadernotex;
121
122 bool isMissing(const char* name);
123
124 bool isNotex(const char* name);
125
126 bool isMissing(const char* name){
127         if ( string_equal( g_notex.c_str(), name ) ) {
128                 return true;
129         }
130         if ( string_equal( g_shadernotex.c_str(), name ) ) {
131                 return true;
132         }
133         return false;
134 }
135
136 bool isNotex(const char* name){
137         if ( string_equal_suffix( name, "/" DEFAULT_NOTEX_BASENAME ) ) {
138                 return true;
139         }
140         if ( string_equal_suffix( name, "/" DEFAULT_SHADERNOTEX_BASENAME ) ) {
141                 return true;
142         }
143         return false;
144 }
145
146 void TextureGroups_addShader( TextureGroups& groups, const char* shaderName ){
147         const char* texture = path_make_relative( shaderName, "textures/" );
148
149         // hide notex / shadernotex images
150         if ( g_TextureBrowser_filterFallback ) {
151                 if ( isNotex( shaderName ) ) {
152                         return;
153                 }
154                 if ( isNotex( texture ) ) {
155                         return;
156                 }
157         }
158
159         if ( texture != shaderName ) {
160                 const char* last = path_remove_directory( texture );
161                 if ( !string_empty( last ) ) {
162                         groups.insert( CopiedString( StringRange( texture, --last ) ) );
163                 }
164         }
165 }
166
167 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addShader> TextureGroupsAddShaderCaller;
168
169 void TextureGroups_addDirectory( TextureGroups& groups, const char* directory ){
170         groups.insert( directory );
171 }
172
173 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addDirectory> TextureGroupsAddDirectoryCaller;
174
175 class DeferredAdjustment
176 {
177 gdouble m_value;
178 guint m_handler;
179
180 typedef void ( *ValueChangedFunction )( void* data, gdouble value );
181
182 ValueChangedFunction m_function;
183 void* m_data;
184
185 static gboolean deferred_value_changed( gpointer data ){
186         reinterpret_cast<DeferredAdjustment*>( data )->m_function(
187                 reinterpret_cast<DeferredAdjustment*>( data )->m_data,
188                 reinterpret_cast<DeferredAdjustment*>( data )->m_value
189                 );
190         reinterpret_cast<DeferredAdjustment*>( data )->m_handler = 0;
191         reinterpret_cast<DeferredAdjustment*>( data )->m_value = 0;
192         return FALSE;
193 }
194
195 public:
196 DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){
197 }
198
199 void flush(){
200         if ( m_handler != 0 ) {
201                 g_source_remove( m_handler );
202                 deferred_value_changed( this );
203         }
204 }
205
206 void value_changed( gdouble value ){
207         m_value = value;
208         if ( m_handler == 0 ) {
209                 m_handler = g_idle_add( deferred_value_changed, this );
210         }
211 }
212
213 static void adjustment_value_changed(ui::Adjustment adjustment, DeferredAdjustment* self ){
214         self->value_changed( gtk_adjustment_get_value(adjustment) );
215 }
216 };
217
218
219 class TextureBrowser;
220
221 typedef ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw> TextureBrowserQueueDrawCaller;
222
223 void TextureBrowser_scrollChanged( void* data, gdouble value );
224
225
226 enum StartupShaders
227 {
228         STARTUPSHADERS_NONE = 0,
229         STARTUPSHADERS_COMMON,
230 };
231
232 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer );
233
234 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
235
236 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer );
237
238 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
239
240 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer );
241
242 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
243
244 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer );
245
246 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
247
248 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer );
249
250 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowserFilterMissingExport;
251
252 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer );
253
254 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowserFilterFallbackExport;
255
256 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer );
257
258 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowserEnableAlphaExport;
259
260 class TextureBrowser
261 {
262 public:
263 int width, height;
264 int originy;
265 int m_nTotalHeight;
266
267 CopiedString shader;
268
269 ui::Window m_parent{ui::null};
270 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
271 ui::VBox m_vframe{ui::null};
272 ui::VBox m_vfiller{ui::null};
273 ui::HBox m_hframe{ui::null};
274 ui::HBox m_hfiller{ui::null};
275 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
276 ui::VBox m_frame{ui::null};
277 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
278 ui::GLArea m_gl_widget{ui::null};
279 ui::Widget m_texture_scroll{ui::null};
280 ui::TreeView m_treeViewTree{ui::New};
281 ui::TreeView m_treeViewTags{ui::null};
282 ui::Frame m_tag_frame{ui::null};
283 ui::ListStore m_assigned_store{ui::null};
284 ui::ListStore m_available_store{ui::null};
285 ui::TreeView m_assigned_tree{ui::null};
286 ui::TreeView m_available_tree{ui::null};
287 ui::Widget m_scr_win_tree{ui::null};
288 ui::Widget m_scr_win_tags{ui::null};
289 ui::Widget m_tag_notebook{ui::null};
290 ui::Button m_search_button{ui::null};
291 ui::Widget m_shader_info_item{ui::null};
292
293 std::set<CopiedString> m_all_tags;
294 ui::ListStore m_all_tags_list{ui::null};
295 std::vector<CopiedString> m_copied_tags;
296 std::set<CopiedString> m_found_shaders;
297
298 ToggleItem m_hideunused_item;
299 ToggleItem m_hidenotex_item;
300 ToggleItem m_showshaders_item;
301 ToggleItem m_showshaderlistonly_item;
302 ToggleItem m_fixedsize_item;
303 ToggleItem m_filternotex_item;
304 ToggleItem m_enablealpha_item;
305
306 guint m_sizeHandler;
307 guint m_exposeHandler;
308
309 bool m_heightChanged;
310 bool m_originInvalid;
311
312 DeferredAdjustment m_scrollAdjustment;
313 FreezePointer m_freezePointer;
314
315 Vector3 color_textureback;
316 // the increment step we use against the wheel mouse
317 std::size_t m_mouseWheelScrollIncrement;
318 std::size_t m_textureScale;
319 // make the texture increments match the grid changes
320 bool m_showShaders;
321 bool m_showTextureScrollbar;
322 StartupShaders m_startupShaders;
323 // if true, the texture window will only display in-use shaders
324 // if false, all the shaders in memory are displayed
325 bool m_hideUnused;
326 bool m_rmbSelected;
327 bool m_searchedTags;
328 bool m_tags;
329 // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true.
330 int m_uniformTextureSize;
331 int m_uniformTextureMinSize;
332
333 // Return the display width of a texture in the texture browser
334 /*void getTextureWH( qtexture_t* tex, int *width, int *height ){
335         if ( !g_TextureBrowser_fixedSize ) {
336                 // Don't use uniform size
337                 *width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
338                 *height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
339
340         }
341         else if ( tex->width >= tex->height ) {
342                 // Texture is square, or wider than it is tall
343                 if ( tex->width >= m_uniformTextureSize ){
344                         *width = m_uniformTextureSize;
345                         *height = (int)( m_uniformTextureSize * ( (float)tex->height / tex->width ) );
346                 }
347                 else if ( tex->width <= m_uniformTextureMinSize ){
348                         *width = m_uniformTextureMinSize;
349                         *height = (int)( m_uniformTextureMinSize * ( (float)tex->height / tex->width ) );
350         }
351         else {
352                         *width = tex->width;
353                         *height = tex->height;
354         }
355         }
356         else {
357                 // Texture taller than it is wide
358                 if ( tex->height >= m_uniformTextureSize ){
359                         *height = m_uniformTextureSize;
360                         *width = (int)( m_uniformTextureSize * ( (float)tex->width / tex->height ) );
361                 }
362                 else if ( tex->height <= m_uniformTextureMinSize ){
363                         *height = m_uniformTextureMinSize;
364                         *width = (int)( m_uniformTextureMinSize * ( (float)tex->width / tex->height ) );
365                 }
366                 else {
367                         *width = tex->width;
368                         *height = tex->height;
369                 }
370         }
371 }
372
373 */
374 void getTextureWH( qtexture_t* tex, int *width, int *height ){
375                 // Don't use uniform size
376                 *width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
377                 *height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
378
379         if ( g_TextureBrowser_fixedSize ){
380                 int W = *width;
381                 int H = *height;
382                 if      ( W >= H ) {
383                         // Texture is square, or wider than it is tall
384                         if ( W >= m_uniformTextureSize ){
385                                 *width = m_uniformTextureSize;
386                                 *height = m_uniformTextureSize * H / W;
387         }
388                         else if ( W <= m_uniformTextureMinSize ){
389                                 *width = m_uniformTextureMinSize;
390                                 *height = m_uniformTextureMinSize * H / W;
391                         }
392         }
393         else {
394                         // Texture taller than it is wide
395                         if ( H >= m_uniformTextureSize ){
396                                 *height = m_uniformTextureSize;
397                                 *width = m_uniformTextureSize * W / H;
398         }
399                         else if ( H <= m_uniformTextureMinSize ){
400                                 *height = m_uniformTextureMinSize;
401                                 *width = m_uniformTextureMinSize * W / H;
402                         }
403                 }
404         }
405 }
406
407 TextureBrowser() :
408         m_texture_scroll( ui::null ),
409         m_hideunused_item( TextureBrowserHideUnusedExport() ),
410         m_hidenotex_item( TextureBrowserFilterFallbackExport() ),
411         m_showshaders_item( TextureBrowserShowShadersExport() ),
412         m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ),
413         m_fixedsize_item( TextureBrowserFixedSizeExport() ),
414         m_filternotex_item( TextureBrowserFilterMissingExport() ),
415         m_enablealpha_item( TextureBrowserEnableAlphaExport() ),
416         m_heightChanged( true ),
417         m_originInvalid( true ),
418         m_scrollAdjustment( TextureBrowser_scrollChanged, this ),
419         color_textureback( 0.25f, 0.25f, 0.25f ),
420         m_mouseWheelScrollIncrement( 64 ),
421         m_textureScale( 50 ),
422         m_showShaders( true ),
423         m_showTextureScrollbar( true ),
424         m_startupShaders( STARTUPSHADERS_NONE ),
425         m_hideUnused( false ),
426         m_rmbSelected( false ),
427         m_searchedTags( false ),
428         m_tags( false ),
429         m_uniformTextureSize( 160 ),
430         m_uniformTextureMinSize( 48 ){
431 }
432 };
433
434 void ( *TextureBrowser_textureSelected )( const char* shader );
435
436
437 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser );
438
439
440 const char* TextureBrowser_getCommonShadersName(){
441         const char* value = g_pGameDescription->getKeyValue( "common_shaders_name" );
442         if ( !string_empty( value ) ) {
443                 return value;
444         }
445         return "Common";
446 }
447
448 const char* TextureBrowser_getCommonShadersDir(){
449         const char* value = g_pGameDescription->getKeyValue( "common_shaders_dir" );
450         if ( !string_empty( value ) ) {
451                 return value;
452         }
453         return "common/";
454 }
455
456 inline int TextureBrowser_fontHeight( TextureBrowser& textureBrowser ){
457         return GlobalOpenGL().m_font->getPixelHeight();
458 }
459
460 const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ){
461         return textureBrowser.shader.c_str();
462 }
463
464 void TextureBrowser_SetStatus( TextureBrowser& textureBrowser, const char* name ){
465         IShader* shader = QERApp_Shader_ForName( name );
466         qtexture_t* q = shader->getTexture();
467         StringOutputStream strTex( 256 );
468         strTex << name << " W: " << Unsigned( q->width ) << " H: " << Unsigned( q->height );
469         shader->DecRef();
470         g_pParentWnd->SetStatusText( g_pParentWnd->m_texture_status, strTex.c_str() );
471 }
472
473 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name );
474
475 void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ){
476         textureBrowser.shader = shader;
477         TextureBrowser_SetStatus( textureBrowser, shader );
478         TextureBrowser_Focus( textureBrowser, shader );
479
480         if ( FindTextureDialog_isOpen() ) {
481                 FindTextureDialog_selectTexture( shader );
482         }
483
484         // disable the menu item "shader info" if no shader was selected
485         IShader* ishader = QERApp_Shader_ForName( shader );
486         CopiedString filename = ishader->getShaderFileName();
487
488         if ( filename.empty() ) {
489                 if ( textureBrowser.m_shader_info_item != NULL ) {
490                         gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
491                 }
492         }
493         else {
494                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, TRUE );
495         }
496
497         ishader->DecRef();
498 }
499
500
501 CopiedString g_TextureBrowser_currentDirectory;
502
503 /*
504    ============================================================================
505
506    TEXTURE LAYOUT
507
508    TTimo: now based on a rundown through all the shaders
509    NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
510    otherwise we may need to rely on a list instead of an array storage
511    ============================================================================
512  */
513
514 class TextureLayout
515 {
516 public:
517 // texture layout functions
518 // TTimo: now based on shaders
519 int current_x, current_y, current_row;
520 };
521
522 void Texture_StartPos( TextureLayout& layout ){
523         layout.current_x = 8;
524         layout.current_y = -8;
525         layout.current_row = 0;
526 }
527
528 void Texture_NextPos( TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y ){
529         qtexture_t* q = current_texture;
530
531         int nWidth, nHeight;
532         textureBrowser.getTextureWH( q, &nWidth, &nHeight );
533         if ( layout.current_x + nWidth > textureBrowser.width - 8 && layout.current_row ) { // go to the next row unless the texture is the first on the row
534                 layout.current_x = 8;
535                 layout.current_y -= layout.current_row + TextureBrowser_fontHeight( textureBrowser ) + 4;
536                 layout.current_row = 0;
537         }
538
539         *x = layout.current_x;
540         *y = layout.current_y;
541
542         // Is our texture larger than the row? If so, grow the
543         // row height to match it
544
545         if ( layout.current_row < nHeight ) {
546                 layout.current_row = nHeight;
547         }
548
549         // never go less than 96, or the names get all crunched up
550         layout.current_x += nWidth < 96 ? 96 : nWidth;
551         layout.current_x += 8;
552 }
553
554 bool TextureSearch_IsShown( const char* name ){
555         std::set<CopiedString>::iterator iter;
556
557         iter = GlobalTextureBrowser().m_found_shaders.find( name );
558
559         if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
560                 return false;
561         }
562         else {
563                 return true;
564         }
565 }
566
567 // if texture_showinuse jump over non in-use textures
568 bool Texture_IsShown( IShader* shader, bool show_shaders, bool hideUnused ){
569         // filter missing shaders
570         // ugly: filter on built-in fallback name after substitution
571         if ( g_TextureBrowser_filterMissing ) {
572                 if ( isMissing( shader->getTexture()->name ) ) {
573                         return false;
574                 }
575         }
576         // filter the fallback (notex/shadernotex) for missing shaders or editor image
577         if ( g_TextureBrowser_filterFallback ) {
578                 if ( isNotex( shader->getName() ) ) {
579                         return false;
580                 }
581                 if ( isNotex( shader->getTexture()->name ) ) {
582                         return false;
583                 }
584         }
585
586         if ( g_TextureBrowser_currentDirectory == "Untagged" ) {
587                 std::set<CopiedString>::iterator iter;
588
589                 iter = GlobalTextureBrowser().m_found_shaders.find( shader->getName() );
590
591                 if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
592                         return false;
593                 }
594                 else {
595                         return true;
596                 }
597         }
598
599         if ( !shader_equal_prefix( shader->getName(), "textures/" ) ) {
600                 return false;
601         }
602
603         if ( !show_shaders && !shader->IsDefault() ) {
604                 return false;
605         }
606
607         if ( hideUnused && !shader->IsInUse() ) {
608                 return false;
609         }
610
611         if ( GlobalTextureBrowser().m_searchedTags ) {
612                 if ( !TextureSearch_IsShown( shader->getName() ) ) {
613                         return false;
614                 }
615                 else {
616                         return true;
617                 }
618         }
619         else {
620                 if ( TextureBrowser_showWads() )
621                 {
622                         if ( g_TextureBrowser_currentDirectory != ""
623                                 && !string_equal( shader->getWadName(), g_TextureBrowser_currentDirectory.c_str() ) )
624                         {
625                                 return false;
626                         }
627                 }
628                 else if ( !shader_equal_prefix( shader_get_textureName( shader->getName() ), g_TextureBrowser_currentDirectory.c_str() ) ) {
629                         return false;
630                 }
631         }
632
633         return true;
634 }
635
636 void TextureBrowser_heightChanged( TextureBrowser& textureBrowser ){
637         textureBrowser.m_heightChanged = true;
638
639         TextureBrowser_updateScroll( textureBrowser );
640         TextureBrowser_queueDraw( textureBrowser );
641 }
642
643 void TextureBrowser_evaluateHeight( TextureBrowser& textureBrowser ){
644         if ( textureBrowser.m_heightChanged ) {
645                 textureBrowser.m_heightChanged = false;
646
647                 textureBrowser.m_nTotalHeight = 0;
648
649                 TextureLayout layout;
650                 Texture_StartPos( layout );
651                 for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
652                 {
653                         IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
654
655                         if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
656                                 continue;
657                         }
658
659                         int x, y;
660                         Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
661                         int nWidth, nHeight;
662                         textureBrowser.getTextureWH( shader->getTexture(), &nWidth, &nHeight );
663                         textureBrowser.m_nTotalHeight = std::max( textureBrowser.m_nTotalHeight, abs( layout.current_y ) + TextureBrowser_fontHeight( textureBrowser ) + nHeight + 4 );
664                 }
665         }
666 }
667
668 int TextureBrowser_TotalHeight( TextureBrowser& textureBrowser ){
669         TextureBrowser_evaluateHeight( textureBrowser );
670         return textureBrowser.m_nTotalHeight;
671 }
672
673 inline const int& min_int( const int& left, const int& right ){
674         return std::min( left, right );
675 }
676
677 void TextureBrowser_clampOriginY( TextureBrowser& textureBrowser ){
678         if ( textureBrowser.originy > 0 ) {
679                 textureBrowser.originy = 0;
680         }
681         int lower = min_int( textureBrowser.height - TextureBrowser_TotalHeight( textureBrowser ), 0 );
682         if ( textureBrowser.originy < lower ) {
683                 textureBrowser.originy = lower;
684         }
685 }
686
687 int TextureBrowser_getOriginY( TextureBrowser& textureBrowser ){
688         if ( textureBrowser.m_originInvalid ) {
689                 textureBrowser.m_originInvalid = false;
690                 TextureBrowser_clampOriginY( textureBrowser );
691                 TextureBrowser_updateScroll( textureBrowser );
692         }
693         return textureBrowser.originy;
694 }
695
696 void TextureBrowser_setOriginY( TextureBrowser& textureBrowser, int originy ){
697         textureBrowser.originy = originy;
698         TextureBrowser_clampOriginY( textureBrowser );
699         TextureBrowser_updateScroll( textureBrowser );
700         TextureBrowser_queueDraw( textureBrowser );
701 }
702
703
704 Signal0 g_activeShadersChangedCallbacks;
705
706 void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handler ){
707         g_activeShadersChangedCallbacks.connectLast( handler );
708 }
709
710 void TextureBrowser_constructTreeStore();
711
712 class ShadersObserver : public ModuleObserver
713 {
714 Signal0 m_realiseCallbacks;
715 public:
716 void realise(){
717         m_realiseCallbacks();
718         TextureBrowser_constructTreeStore();
719 }
720
721 void unrealise(){
722 }
723
724 void insert( const SignalHandler& handler ){
725         m_realiseCallbacks.connectLast( handler );
726 }
727 };
728
729 namespace
730 {
731 ShadersObserver g_ShadersObserver;
732 }
733
734 void TextureBrowser_addShadersRealiseCallback( const SignalHandler& handler ){
735         g_ShadersObserver.insert( handler );
736 }
737
738 void TextureBrowser_activeShadersChanged( TextureBrowser& textureBrowser ){
739         TextureBrowser_heightChanged( textureBrowser );
740         textureBrowser.m_originInvalid = true;
741
742         g_activeShadersChangedCallbacks();
743 }
744
745 struct TextureBrowser_ShowScrollbar {
746         static void Export(const TextureBrowser &self, const Callback<void(bool)> &returnz) {
747                 returnz(self.m_showTextureScrollbar);
748         }
749
750         static void Import(TextureBrowser &self, bool value) {
751                 self.m_showTextureScrollbar = value;
752                 if (self.m_texture_scroll) {
753                         self.m_texture_scroll.visible(self.m_showTextureScrollbar);
754                         TextureBrowser_updateScroll(self);
755                 }
756         }
757 };
758
759
760 /*
761    ==============
762    TextureBrowser_ShowDirectory
763    relies on texture_directory global for the directory to use
764    1) Load the shaders for the given directory
765    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
766    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
767    available through the IShaders interface
768    NOTE: for texture window layout:
769    all shaders are stored with alphabetical order after load
770    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
771    ( the GL textures are not flushed though)
772    ==============
773  */
774
775 bool endswith( const char *haystack, const char *needle ){
776         size_t lh = strlen( haystack );
777         size_t ln = strlen( needle );
778         if ( lh < ln ) {
779                 return false;
780         }
781         return !memcmp( haystack + ( lh - ln ), needle, ln );
782 }
783
784 bool texture_name_ignore( const char* name ){
785         StringOutputStream strTemp( string_length( name ) );
786         strTemp << LowerCase( name );
787
788         return
789                 endswith( strTemp.c_str(), ".specular" ) ||
790                 endswith( strTemp.c_str(), ".glow" ) ||
791                 endswith( strTemp.c_str(), ".bump" ) ||
792                 endswith( strTemp.c_str(), ".diffuse" ) ||
793                 endswith( strTemp.c_str(), ".blend" ) ||
794                 endswith( strTemp.c_str(), ".alpha" ) ||
795                 endswith( strTemp.c_str(), "_alpha" ) ||
796                 /* Quetoo */
797                 endswith( strTemp.c_str(), "_h" ) ||
798                 endswith( strTemp.c_str(), "_local" ) ||
799                 endswith( strTemp.c_str(), "_nm" ) ||
800                 endswith( strTemp.c_str(), "_s" ) ||
801                 /* DarkPlaces */
802                 endswith( strTemp.c_str(), "_bump" ) ||
803                 endswith( strTemp.c_str(), "_glow" ) ||
804                 endswith( strTemp.c_str(), "_gloss" ) ||
805                 endswith( strTemp.c_str(), "_luma" ) ||
806                 endswith( strTemp.c_str(), "_norm" ) ||
807                 endswith( strTemp.c_str(), "_pants" ) ||
808                 endswith( strTemp.c_str(), "_shirt" ) ||
809                 endswith( strTemp.c_str(), "_reflect" ) ||
810                 /* Unvanquished */
811                 endswith( strTemp.c_str(), "_d" ) ||
812                 endswith( strTemp.c_str(), "_n" ) ||
813                 endswith( strTemp.c_str(), "_p" ) ||
814                 endswith( strTemp.c_str(), "_g" ) ||
815                 endswith( strTemp.c_str(), "_a" ) ||
816                 0;
817 }
818
819 class LoadShaderVisitor : public Archive::Visitor
820 {
821 public:
822 void visit( const char* name ){
823         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
824         shader->DecRef();
825         shader->setWadName( g_TextureBrowser_currentDirectory.c_str() );
826 }
827 };
828
829 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
830
831 ui::Widget g_page_textures{ui::null};
832
833 void TextureBrowser_toggleShow(){
834         GroupDialog_showPage( g_page_textures );
835 }
836
837
838 void TextureBrowser_updateTitle(){
839         GroupDialog_updatePageTitle( g_page_textures );
840 }
841
842
843 class TextureCategoryLoadShader
844 {
845 const char* m_directory;
846 std::size_t& m_count;
847 public:
848 using func = void(const char *);
849
850 TextureCategoryLoadShader( const char* directory, std::size_t& count )
851         : m_directory( directory ), m_count( count ){
852         m_count = 0;
853 }
854
855 void operator()( const char* name ) const {
856         if ( shader_equal_prefix( name, "textures/" )
857                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
858                 ++m_count;
859                 // request the shader, this will load the texture if needed
860                 // this Shader_ForName call is a kind of hack
861                 IShader *pFoo = QERApp_Shader_ForName( name );
862                 pFoo->DecRef();
863         }
864 }
865 };
866
867 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
868         // Doom3-like dds/ prefix (used by DarkPlaces).
869         // When we list dds/textures/ folder,
870         // store the texture names without dds/ prefix.
871         if ( !strncmp( "dds/", directory, 4 ) )
872         {
873                 directory = &directory[ 4 ];
874         }
875
876         StringOutputStream name( 256 );
877         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
878
879         if ( texture_name_ignore( name.c_str() ) ) {
880                 return;
881         }
882
883         if ( !shader_valid( name.c_str() ) ) {
884                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
885                 return;
886         }
887
888         // if a texture is already in use to represent a shader, ignore it
889         IShader* shader = QERApp_Shader_ForName( name.c_str() );
890         shader->DecRef();
891 }
892
893 typedef ConstPointerCaller<char, void(const char*), TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
894
895 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
896 {
897 const char* m_dirstring;
898 public:
899 LoadTexturesByTypeVisitor( const char* dirstring )
900         : m_dirstring( dirstring ){
901 }
902
903 void visit( const char* minor, const _QERPlugImageTable& table ) const {
904         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
905 }
906 };
907
908 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
909         if ( TextureBrowser_showWads() ) {
910                 g_TextureBrowser_currentDirectory = directory;
911                 TextureBrowser_heightChanged( textureBrowser );
912
913                 Archive* archive = GlobalFileSystem().getArchive( directory );
914                 if ( archive != nullptr )
915                 {
916                 LoadShaderVisitor visitor;
917                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
918
919                         // Doom3-like dds/ prefix (used by DarkPlaces).
920                         archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "dds/textures/" );
921                 }
922                 else if ( extension_equal_i( path_get_extension( directory ), "wad" ) )
923                 {
924                         globalErrorStream() << "Failed to load " << directory << "\n";
925                 }
926         }
927         else
928         {
929                 g_TextureBrowser_currentDirectory = directory;
930                 TextureBrowser_heightChanged( textureBrowser );
931
932                 std::size_t shaders_count;
933                 GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
934                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
935
936                 if ( g_pGameDescription->mGameType != "doom3" ) {
937                         // load remaining texture files
938
939                         StringOutputStream dirstring( 64 );
940                         dirstring << "textures/" << directory;
941
942                         {
943                                 LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
944                                 Radiant_getImageModules().foreachModule( visitor );
945                         }
946
947                         // Doom3-like dds/ prefix (used by DarkPlaces).
948                         dirstring.clear();
949                         dirstring << "dds/textures/" << directory;
950
951                         {
952                                 LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
953                                 Radiant_getImageModules().foreachModule( visitor );
954                         }
955                 }
956         }
957
958         // we'll display the newly loaded textures + all the ones already in use
959         TextureBrowser_SetHideUnused( textureBrowser, false );
960
961         TextureBrowser_updateTitle();
962 }
963
964 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
965         g_TextureBrowser_currentDirectory = directory;
966         TextureBrowser_heightChanged( textureBrowser );
967
968         std::size_t shaders_count;
969         GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
970         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
971
972         if ( g_pGameDescription->mGameType != "doom3" ) {
973                 // load remaining texture files
974                 StringOutputStream dirstring( 64 );
975                 dirstring << "textures/" << directory;
976
977                 {
978                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
979                         Radiant_getImageModules().foreachModule( visitor );
980                 }
981
982                 // Doom3-like dds/ prefix (used by DarkPlaces).
983                 dirstring.clear();
984                 dirstring << "dds/textures/" << directory;
985
986                 {
987                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
988                         Radiant_getImageModules().foreachModule( visitor );
989                 }
990         }
991
992         // we'll display the newly loaded textures + all the ones already in use
993         TextureBrowser_SetHideUnused( textureBrowser, false );
994 }
995
996
997 bool TextureBrowser_hideUnused();
998
999 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer ){
1000         importer( TextureBrowser_hideUnused() );
1001 }
1002
1003 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
1004
1005 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer ){
1006         importer( GlobalTextureBrowser().m_showShaders );
1007 }
1008
1009 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
1010
1011 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer ){
1012         importer( g_TextureBrowser_shaderlistOnly );
1013 }
1014
1015 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
1016
1017 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer ){
1018         importer( g_TextureBrowser_fixedSize );
1019 }
1020
1021 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
1022
1023 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer ){
1024         importer( g_TextureBrowser_filterMissing );
1025 }
1026
1027 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowser_filterMissingExport;
1028
1029 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer ){
1030         importer( g_TextureBrowser_filterFallback );
1031 }
1032
1033 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowser_filterFallbackExport;
1034
1035 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer ){
1036         importer( g_TextureBrowser_enableAlpha );
1037 }
1038
1039 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowser_enableAlphaExport;
1040
1041 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
1042         if ( hideUnused ) {
1043                 textureBrowser.m_hideUnused = true;
1044         }
1045         else
1046         {
1047                 textureBrowser.m_hideUnused = false;
1048         }
1049
1050         textureBrowser.m_hideunused_item.update();
1051
1052         TextureBrowser_heightChanged( textureBrowser );
1053         textureBrowser.m_originInvalid = true;
1054 }
1055
1056 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
1057         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
1058                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getCommonShadersDir() );
1059         }
1060 }
1061
1062
1063 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
1064 // it might need to be split in parts or moved out .. dunno
1065 // scroll origin so the specified texture is completely on screen
1066 // if current texture is not displayed, nothing is changed
1067 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
1068         TextureLayout layout;
1069         // scroll origin so the texture is completely on screen
1070         Texture_StartPos( layout );
1071
1072         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1073         {
1074                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1075
1076                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1077                         continue;
1078                 }
1079
1080                 int x, y;
1081                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1082                 qtexture_t* q = shader->getTexture();
1083                 if ( !q ) {
1084                         break;
1085                 }
1086
1087                 // we have found when texdef->name and the shader name match
1088                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
1089                 if ( shader_equal( name, shader->getName() ) ) {
1090                         int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) )
1091                                                                 + 2 * TextureBrowser_fontHeight( textureBrowser );
1092
1093                         int originy = TextureBrowser_getOriginY( textureBrowser );
1094                         if ( y > originy ) {
1095                                 originy = y;
1096                         }
1097
1098                         if ( y - textureHeight < originy - textureBrowser.height ) {
1099                                 originy = ( y - textureHeight ) + textureBrowser.height;
1100                         }
1101
1102                         TextureBrowser_setOriginY( textureBrowser, originy );
1103                         return;
1104                 }
1105         }
1106 }
1107
1108 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
1109         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
1110
1111         TextureLayout layout;
1112         Texture_StartPos( layout );
1113         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1114         {
1115                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1116
1117                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1118                         continue;
1119                 }
1120
1121                 int x, y;
1122                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1123                 qtexture_t  *q = shader->getTexture();
1124                 if ( !q ) {
1125                         break;
1126                 }
1127
1128                 int nWidth, nHeight;
1129                 textureBrowser.getTextureWH( q, &nWidth, &nHeight );
1130                 if ( mx > x && mx - x < nWidth
1131                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
1132                         return shader;
1133                 }
1134         }
1135
1136         return 0;
1137 }
1138
1139 /*
1140    ==============
1141    SelectTexture
1142
1143    By mouse click
1144    ==============
1145  */
1146 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
1147         IShader* shader = Texture_At( textureBrowser, mx, my );
1148         if ( shader != 0 ) {
1149                 if ( bShift ) {
1150                         if ( shader->IsDefault() ) {
1151                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
1152                         }
1153                         else{
1154                                 ViewShader( shader->getShaderFileName(), shader->getName() );
1155                         }
1156                 }
1157                 else
1158                 {
1159                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
1160                         TextureBrowser_textureSelected( shader->getName() );
1161
1162                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
1163                                 UndoableCommand undo( "textureNameSetSelected" );
1164                                 Select_SetShader( shader->getName() );
1165                         }
1166                 }
1167         }
1168 }
1169
1170 /*
1171    ============================================================================
1172
1173    MOUSE ACTIONS
1174
1175    ============================================================================
1176  */
1177
1178 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
1179         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
1180         if ( y != 0 ) {
1181                 int scale = 1;
1182
1183                 if ( state & GDK_SHIFT_MASK ) {
1184                         scale = 4;
1185                 }
1186
1187                 int originy = TextureBrowser_getOriginY( textureBrowser );
1188                 originy += y * scale;
1189                 TextureBrowser_setOriginY( textureBrowser, originy );
1190         }
1191 }
1192
1193 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
1194         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_gl_widget, TextureBrowser_trackingDelta, &textureBrowser );
1195 }
1196
1197 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
1198         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_gl_widget );
1199 }
1200
1201 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
1202         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
1203 }
1204
1205 /*
1206    ============================================================================
1207
1208    DRAWING
1209
1210    ============================================================================
1211  */
1212
1213 /*
1214    ============
1215    Texture_Draw
1216    TTimo: relying on the shaders list to display the textures
1217    we must query all qtexture_t* to manage and display through the IShaders interface
1218    this allows a plugin to completely override the texture system
1219    ============
1220  */
1221 void Texture_Draw( TextureBrowser& textureBrowser ){
1222         int originy = TextureBrowser_getOriginY( textureBrowser );
1223
1224         glClearColor( textureBrowser.color_textureback[0],
1225                                   textureBrowser.color_textureback[1],
1226                                   textureBrowser.color_textureback[2],
1227                                   0 );
1228
1229         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1230         glMatrixMode( GL_PROJECTION );
1231         glLoadIdentity();
1232
1233         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1234         glDisable( GL_DEPTH_TEST );
1235         if ( g_TextureBrowser_enableAlpha ) {
1236                 glEnable( GL_BLEND );
1237                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1238         }
1239         else {
1240                 glDisable( GL_BLEND );
1241         }
1242         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1243         glEnable( GL_TEXTURE_2D );
1244
1245         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1246
1247         int last_y = 0, last_height = 0;
1248
1249         TextureLayout layout;
1250         Texture_StartPos( layout );
1251         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1252         {
1253                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1254
1255                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1256                         continue;
1257                 }
1258
1259                 int x, y;
1260                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1261                 qtexture_t *q = shader->getTexture();
1262                 if ( !q ) {
1263                         break;
1264                 }
1265
1266                 int nWidth, nHeight;
1267                 textureBrowser.getTextureWH( q, &nWidth, &nHeight );
1268
1269                 if ( y != last_y ) {
1270                         last_y = y;
1271                         last_height = 0;
1272                 }
1273                 last_height = std::max( nHeight, last_height );
1274
1275                 // Is this texture visible?
1276                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1277                          && ( y > originy - textureBrowser.height ) ) {
1278                         // borders rules:
1279                         // if it's the current texture, draw a thick red line, else:
1280                         // shaders have a white border, simple textures don't
1281                         // if !texture_showinuse: (some textures displayed may not be in use)
1282                         // draw an additional square around with 0.5 1 0.5 color
1283                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1284                                 glLineWidth( 3 );
1285                                 if ( textureBrowser.m_rmbSelected ) {
1286                                         glColor3f( 0,0,1 );
1287                                 }
1288                                 else {
1289                                         glColor3f( 1,0,0 );
1290                                 }
1291                                 glDisable( GL_TEXTURE_2D );
1292
1293                                 glBegin( GL_LINE_LOOP );
1294                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1295                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1296                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1297                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1298                                 glEnd();
1299
1300                                 glEnable( GL_TEXTURE_2D );
1301                                 glLineWidth( 1 );
1302                         }
1303                         else
1304                         {
1305                                 glLineWidth( 1 );
1306                                 // shader border:
1307                                 if ( !shader->IsDefault() ) {
1308                                         glColor3f( 1,1,1 );
1309                                         glDisable( GL_TEXTURE_2D );
1310
1311                                         glBegin( GL_LINE_LOOP );
1312                                         glVertex2i( x - 1,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1313                                         glVertex2i( x - 1,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1314                                         glVertex2i( x + 1 + nWidth,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1315                                         glVertex2i( x + 1 + nWidth,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1316                                         glEnd();
1317                                         glEnable( GL_TEXTURE_2D );
1318                                 }
1319
1320                                 // highlight in-use textures
1321                                 if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1322                                         glColor3f( 0.5,1,0.5 );
1323                                         glDisable( GL_TEXTURE_2D );
1324                                         glBegin( GL_LINE_LOOP );
1325                                         glVertex2i( x - 3,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1326                                         glVertex2i( x - 3,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1327                                         glVertex2i( x + 3 + nWidth,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1328                                         glVertex2i( x + 3 + nWidth,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1329                                         glEnd();
1330                                         glEnable( GL_TEXTURE_2D );
1331                                 }
1332                         }
1333
1334                         // draw checkerboard for transparent textures
1335                         if ( g_TextureBrowser_enableAlpha )
1336                         {
1337                                 glDisable( GL_TEXTURE_2D );
1338                                 glBegin( GL_QUADS );
1339                                 int font_height = TextureBrowser_fontHeight( textureBrowser );
1340                                 for ( int i = 0; i < nHeight; i += 8 )
1341                                 {
1342                                         for ( int j = 0; j < nWidth; j += 8 )
1343                                         {
1344                                                 unsigned char color = (i + j) / 8 % 2 ? 0x66 : 0x99;
1345                                                 glColor3ub( color, color, color );
1346                                                 int left = j;
1347                                                 int right = std::min(j+8, nWidth);
1348                                                 int top = i;
1349                                                 int bottom = std::min(i+8, nHeight);
1350                                                 glVertex2i(x + right, y - nHeight - font_height + top);
1351                                                 glVertex2i(x + left,  y - nHeight - font_height + top);
1352                                                 glVertex2i(x + left,  y - nHeight - font_height + bottom);
1353                                                 glVertex2i(x + right, y - nHeight - font_height + bottom);
1354                                         }
1355                                 }
1356                                 glEnd();
1357                                 glEnable( GL_TEXTURE_2D );
1358                         }
1359
1360                         // Draw the texture
1361                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1362                         GlobalOpenGL_debugAssertNoErrors();
1363                         glColor3f( 1,1,1 );
1364                         glBegin( GL_QUADS );
1365                         glTexCoord2i( 0,0 );
1366                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1367                         glTexCoord2i( 1,0 );
1368                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1369                         glTexCoord2i( 1,1 );
1370                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1371                         glTexCoord2i( 0,1 );
1372                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1373                         glEnd();
1374
1375                         // draw the texture name
1376                         glDisable( GL_TEXTURE_2D );
1377                         glColor3f( 1,1,1 );
1378
1379                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 5 );
1380
1381                         // don't draw the directory name
1382                         const char* name = shader->getName();
1383                         name += strlen( name );
1384                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1385                                 name--;
1386
1387                         GlobalOpenGL().drawString( name );
1388                         glEnable( GL_TEXTURE_2D );
1389                 }
1390
1391                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1392         }
1393
1394
1395         // reset the current texture
1396         glBindTexture( GL_TEXTURE_2D, 0 );
1397         //qglFinish();
1398 }
1399
1400 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1401         if ( textureBrowser.m_gl_widget ) {
1402                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1403         }
1404 }
1405
1406
1407 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1408         textureBrowser.m_textureScale = scale;
1409
1410         TextureBrowser_queueDraw( textureBrowser );
1411 }
1412
1413 void TextureBrowser_setUniformSize( TextureBrowser& textureBrowser, std::size_t scale ){
1414         textureBrowser.m_uniformTextureSize = scale;
1415
1416         TextureBrowser_queueDraw( textureBrowser );
1417 }
1418
1419 void TextureBrowser_setUniformMinSize( TextureBrowser& textureBrowser, std::size_t scale ){
1420         textureBrowser.m_uniformTextureMinSize = scale;
1421
1422         TextureBrowser_queueDraw( textureBrowser );
1423 }
1424
1425 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1426         int originy = TextureBrowser_getOriginY( textureBrowser );
1427
1428         if ( bUp ) {
1429                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1430         }
1431         else
1432         {
1433                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1434         }
1435
1436         TextureBrowser_setOriginY( textureBrowser, originy );
1437 }
1438
1439 XmlTagBuilder TagBuilder;
1440
1441 enum
1442 {
1443         TAG_COLUMN,
1444         N_COLUMNS
1445 };
1446
1447 void BuildStoreAssignedTags( ui::ListStore store, const char* shader, TextureBrowser* textureBrowser ){
1448         GtkTreeIter iter;
1449
1450         store.clear();
1451
1452         std::vector<CopiedString> assigned_tags;
1453         TagBuilder.GetShaderTags( shader, assigned_tags );
1454
1455         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1456         {
1457                 store.append(TAG_COLUMN, assigned_tags[i].c_str());
1458         }
1459 }
1460
1461 void BuildStoreAvailableTags(   ui::ListStore storeAvailable,
1462                                                                 ui::ListStore storeAssigned,
1463                                                                 const std::set<CopiedString>& allTags,
1464                                                                 TextureBrowser* textureBrowser ){
1465         GtkTreeIter iterAssigned;
1466         GtkTreeIter iterAvailable;
1467         std::set<CopiedString>::const_iterator iterAll;
1468         gchar* tag_assigned;
1469
1470         storeAvailable.clear();
1471
1472         bool row = gtk_tree_model_get_iter_first(storeAssigned, &iterAssigned ) != 0;
1473
1474         if ( !row ) { // does the shader have tags assigned?
1475                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1476                 {
1477                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1478                 }
1479         }
1480         else
1481         {
1482                 while ( row ) // available tags = all tags - assigned tags
1483                 {
1484                         gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1485
1486                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1487                         {
1488                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1489                                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1490                                 }
1491                                 else
1492                                 {
1493                                         row = gtk_tree_model_iter_next(storeAssigned, &iterAssigned ) != 0;
1494
1495                                         if ( row ) {
1496                                                 gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1497                                         }
1498                                 }
1499                         }
1500                 }
1501         }
1502 }
1503
1504 gboolean TextureBrowser_button_press( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1505         if ( event->type == GDK_BUTTON_PRESS ) {
1506                 if ( event->button == 3 ) {
1507                         if ( textureBrowser->m_tags ) {
1508                                 textureBrowser->m_rmbSelected = true;
1509                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1510
1511                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1512                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1513                                 textureBrowser->m_heightChanged = true;
1514                                 textureBrowser->m_tag_frame.show();
1515
1516                 ui::process();
1517
1518                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1519                         }
1520                         else
1521                         {
1522                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1523                         }
1524                 }
1525                 else if ( event->button == 1 ) {
1526                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1527
1528                         if ( textureBrowser->m_tags ) {
1529                                 textureBrowser->m_rmbSelected = false;
1530                                 textureBrowser->m_tag_frame.hide();
1531                         }
1532                 }
1533         }
1534         return FALSE;
1535 }
1536
1537 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1538         if ( event->type == GDK_BUTTON_RELEASE ) {
1539                 if ( event->button == 3 ) {
1540                         if ( !textureBrowser->m_tags ) {
1541                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1542                         }
1543                 }
1544         }
1545         return FALSE;
1546 }
1547
1548 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1549         return FALSE;
1550 }
1551
1552 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1553         if ( event->direction == GDK_SCROLL_UP ) {
1554                 TextureBrowser_MouseWheel( *textureBrowser, true );
1555         }
1556         else if ( event->direction == GDK_SCROLL_DOWN ) {
1557                 TextureBrowser_MouseWheel( *textureBrowser, false );
1558         }
1559         return FALSE;
1560 }
1561
1562 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1563         //globalOutputStream() << "vertical scroll\n";
1564         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1565 }
1566
1567 static void TextureBrowser_verticalScroll(ui::Adjustment adjustment, TextureBrowser* textureBrowser ){
1568         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1569 }
1570
1571 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1572         if ( textureBrowser.m_showTextureScrollbar ) {
1573                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1574
1575                 totalHeight = std::max( totalHeight, textureBrowser.height );
1576
1577         auto vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1578
1579                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1580                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1581                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1582                 gtk_adjustment_set_step_increment(vadjustment, 20);
1583                 gtk_adjustment_set_lower(vadjustment, 0);
1584                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1585
1586                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1587         }
1588 }
1589
1590 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1591         textureBrowser->width = allocation->width;
1592         textureBrowser->height = allocation->height;
1593         TextureBrowser_heightChanged( *textureBrowser );
1594         textureBrowser->m_originInvalid = true;
1595         TextureBrowser_queueDraw( *textureBrowser );
1596         return FALSE;
1597 }
1598
1599 void TextureBrowser_redraw( TextureBrowser* textureBrowser ){
1600         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1601                 GlobalOpenGL_debugAssertNoErrors();
1602                 TextureBrowser_evaluateHeight( *textureBrowser );
1603                 Texture_Draw( *textureBrowser );
1604                 GlobalOpenGL_debugAssertNoErrors();
1605                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1606         }
1607 }
1608
1609 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1610         TextureBrowser_redraw( textureBrowser );
1611         return FALSE;
1612 }
1613
1614 TextureBrowser& GlobalTextureBrowser(){
1615         static TextureBrowser textureBrowser;
1616         return textureBrowser;
1617 }
1618
1619 bool TextureBrowser_hideUnused(){
1620         return GlobalTextureBrowser().m_hideUnused;
1621 }
1622
1623 void TextureBrowser_ToggleHideUnused(){
1624         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1625         if ( textureBrowser.m_hideUnused ) {
1626                 TextureBrowser_SetHideUnused( textureBrowser, false );
1627         }
1628         else
1629         {
1630                 TextureBrowser_SetHideUnused( textureBrowser, true );
1631         }
1632 }
1633
1634 const char* TextureGroups_transformDirName( const char* dirName, StringOutputStream *archiveName )
1635 {
1636         if ( TextureBrowser_showWads() ) {
1637                 archiveName->clear();
1638                 *archiveName << StringRange( path_get_filename_start( dirName ), path_get_filename_base_end( dirName ) ) \
1639                         << "." << path_get_extension( dirName );
1640                 return archiveName->c_str();
1641         }
1642         return dirName;
1643 }
1644
1645 void TextureGroups_constructTreeModel( TextureGroups groups, ui::TreeStore store ){
1646         // put the information from the old textures menu into a treeview
1647         GtkTreeIter iter, child;
1648
1649         TextureGroups::const_iterator i = groups.begin();
1650         while ( i != groups.end() )
1651         {
1652                 StringOutputStream archiveName;
1653                 StringOutputStream nextArchiveName;
1654                 const char* dirName = TextureGroups_transformDirName( ( *i ).c_str(), &archiveName );
1655
1656                 const char* firstUnderscore = strchr( dirName, '_' );
1657                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1658
1659                 TextureGroups::const_iterator next = i;
1660                 ++next;
1661
1662                 if ( firstUnderscore != 0
1663                          && next != groups.end()
1664                          && string_equal_start( TextureGroups_transformDirName( ( *next ).c_str(), &nextArchiveName ), dirRoot ) ) {
1665                         gtk_tree_store_append( store, &iter, NULL );
1666                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1667
1668                         // keep going...
1669                         while ( i != groups.end() && string_equal_start( TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), dirRoot ) )
1670                         {
1671                                 gtk_tree_store_append( store, &child, &iter );
1672                                 gtk_tree_store_set( store, &child, 0, TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), -1 );
1673                                 ++i;
1674                         }
1675                 }
1676                 else
1677                 {
1678                         gtk_tree_store_append( store, &iter, NULL );
1679                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1680                         ++i;
1681                 }
1682         }
1683 }
1684
1685 TextureGroups TextureGroups_constructTreeView(){
1686         TextureGroups groups;
1687
1688         if ( TextureBrowser_showWads() ) {
1689                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1690         }
1691         else
1692         {
1693                 // scan texture dirs and pak files only if not restricting to shaderlist
1694                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1695                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1696                 }
1697
1698                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1699         }
1700
1701         return groups;
1702 }
1703
1704 void TextureBrowser_constructTreeStore(){
1705         TextureGroups groups = TextureGroups_constructTreeView();
1706         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1707         TextureGroups_constructTreeModel( groups, store );
1708
1709         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTree, store);
1710
1711         g_object_unref( G_OBJECT( store ) );
1712 }
1713
1714 void TextureBrowser_constructTreeStoreTags(){
1715         TextureGroups groups;
1716         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1717         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1718         auto model = GlobalTextureBrowser().m_all_tags_list;
1719
1720         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTags, model );
1721
1722         g_object_unref( G_OBJECT( store ) );
1723 }
1724
1725 void TreeView_onRowActivated( ui::TreeView treeview, ui::TreePath path, ui::TreeViewColumn col, gpointer userdata ){
1726         GtkTreeIter iter;
1727
1728     auto model = gtk_tree_view_get_model(treeview );
1729
1730         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1731                 gchar dirName[1024];
1732
1733                 gchar* buffer;
1734                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1735                 strcpy( dirName, buffer );
1736                 g_free( buffer );
1737
1738                 GlobalTextureBrowser().m_searchedTags = false;
1739
1740                 if ( !TextureBrowser_showWads() ) {
1741                         strcat( dirName, "/" );
1742                 }
1743
1744                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1745                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1746                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1747                 //deactivate, so SPACE and RETURN wont be broken for 2d
1748                 gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( treeview ) ) ), NULL );
1749         }
1750 }
1751
1752 void TextureBrowser_createTreeViewTree(){
1753         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1754         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTree, FALSE );
1755
1756         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTree, FALSE );
1757         textureBrowser.m_treeViewTree.connect( "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1758
1759         auto renderer = ui::CellRendererText(ui::New);
1760         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTree, -1, "", renderer, "text", 0, NULL );
1761
1762         TextureBrowser_constructTreeStore();
1763 }
1764
1765 void TextureBrowser_addTag();
1766
1767 void TextureBrowser_renameTag();
1768
1769 void TextureBrowser_deleteTag();
1770
1771 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1772         ui::Widget menu = ui::Menu(ui::New);
1773
1774         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1775         menuitem.connect( "activate", (GCallback)TextureBrowser_addTag, treeview );
1776         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1777
1778         menuitem = ui::MenuItem( "Rename tag" );
1779         menuitem.connect( "activate", (GCallback)TextureBrowser_renameTag, treeview );
1780         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1781
1782         menuitem = ui::MenuItem( "Delete tag" );
1783         menuitem.connect( "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1784         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1785
1786         gtk_widget_show_all( menu );
1787
1788         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1789                                         ( event != NULL ) ? event->button : 0,
1790                                         gdk_event_get_time( (GdkEvent*)event ) );
1791 }
1792
1793 gboolean TreeViewTags_onButtonPressed( ui::TreeView treeview, GdkEventButton *event ){
1794         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1795                 GtkTreePath *path;
1796         auto selection = gtk_tree_view_get_selection(treeview );
1797
1798                 if ( gtk_tree_view_get_path_at_pos(treeview, event->x, event->y, &path, NULL, NULL, NULL ) ) {
1799                         gtk_tree_selection_unselect_all( selection );
1800                         gtk_tree_selection_select_path( selection, path );
1801                         gtk_tree_path_free( path );
1802                 }
1803
1804                 TextureBrowser_createContextMenu( treeview, event );
1805                 return TRUE;
1806         }
1807         return FALSE;
1808 }
1809
1810 void TextureBrowser_createTreeViewTags(){
1811         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1812         textureBrowser.m_treeViewTags = ui::TreeView(ui::New);
1813         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTags, FALSE );
1814
1815         textureBrowser.m_treeViewTags.connect( "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1816
1817         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTags, FALSE );
1818
1819         auto renderer = ui::CellRendererText(ui::New);
1820         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTags, -1, "", renderer, "text", 0, NULL );
1821
1822         TextureBrowser_constructTreeStoreTags();
1823 }
1824
1825 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1826         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1827         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1828
1829         if ( g_Layout_enableDetachableMenus.m_value ) {
1830                 menu_tearoff( menu );
1831         }
1832
1833         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1834         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1835                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1836         }
1837
1838         // hide notex and shadernotex on texture browser: no one wants to apply them
1839         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1840
1841         menu_separator( menu );
1842
1843         create_menu_item_with_mnemonic( menu, "Show All", "ShowAllTextures" );
1844
1845         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1846         if ( g_pGameDescription->mGameType == "doom3" || TextureBrowser_showWads() ) {
1847                 textureBrowser.m_showShaders = true;
1848         }
1849         else
1850         {
1851                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1852         }
1853
1854         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1855                 create_check_menu_item_with_mnemonic( menu, "Shaders Only", "ToggleShowShaderlistOnly" );
1856         }
1857         if ( textureBrowser.m_tags ) {
1858                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1859         }
1860
1861         menu_separator( menu );
1862         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1863         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1864
1865         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1866                 menu_separator( menu );
1867                 textureBrowser.m_shader_info_item = ui::Widget(create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo"  ));
1868                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
1869         }
1870
1871
1872         return textures_menu_item;
1873 }
1874
1875 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1876         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1877
1878         if ( g_Layout_enableDetachableMenus.m_value ) {
1879                 menu_tearoff( menu );
1880         }
1881
1882         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1883         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1884
1885         return textures_menu_item;
1886 }
1887
1888 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1889         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1890
1891         if ( g_Layout_enableDetachableMenus.m_value ) {
1892                 menu_tearoff( menu );
1893         }
1894
1895         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1896         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1897         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1898         menu_separator( menu );
1899         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1900         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1901
1902         return textures_menu_item;
1903 }
1904
1905 gboolean TextureBrowser_tagMoveHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
1906         g_assert( selected != NULL );
1907
1908     auto rowref = gtk_tree_row_reference_new( model, path );
1909         *selected = g_slist_append( *selected, rowref );
1910
1911         return FALSE;
1912 }
1913
1914 void TextureBrowser_assignTags(){
1915         GSList* selected = NULL;
1916         GSList* node;
1917         gchar* tag_assigned;
1918         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1919
1920         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
1921
1922         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1923
1924         if ( selected != NULL ) {
1925                 for ( node = selected; node != NULL; node = node->next )
1926                 {
1927             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1928
1929                         if ( path ) {
1930                                 GtkTreeIter iter;
1931
1932                                 if ( gtk_tree_model_get_iter(textureBrowser.m_available_store, &iter, path ) ) {
1933                                         gtk_tree_model_get(textureBrowser.m_available_store, &iter, TAG_COLUMN, &tag_assigned, -1 );
1934                                         if ( !TagBuilder.CheckShaderTag( textureBrowser.shader.c_str() ) ) {
1935                                                 // create a custom shader/texture entry
1936                                                 IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
1937                                                 CopiedString filename = ishader->getShaderFileName();
1938
1939                                                 if ( filename.empty() ) {
1940                                                         // it's a texture
1941                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, TEXTURE );
1942                                                 }
1943                                                 else {
1944                                                         // it's a shader
1945                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, SHADER );
1946                                                 }
1947                                                 ishader->DecRef();
1948                                         }
1949                                         TagBuilder.AddShaderTag( textureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
1950
1951                                         gtk_list_store_remove( textureBrowser.m_available_store, &iter );
1952                                         textureBrowser.m_assigned_store.append(TAG_COLUMN, tag_assigned);
1953                                 }
1954                         }
1955                 }
1956
1957                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1958
1959                 // Save changes
1960                 TagBuilder.SaveXmlDoc();
1961         }
1962         g_slist_free( selected );
1963 }
1964
1965 void TextureBrowser_removeTags(){
1966         GSList* selected = NULL;
1967         GSList* node;
1968         gchar* tag;
1969         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1970
1971         auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
1972
1973         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1974
1975         if ( selected != NULL ) {
1976                 for ( node = selected; node != NULL; node = node->next )
1977                 {
1978             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1979
1980                         if ( path ) {
1981                                 GtkTreeIter iter;
1982
1983                                 if ( gtk_tree_model_get_iter(textureBrowser.m_assigned_store, &iter, path ) ) {
1984                                         gtk_tree_model_get(textureBrowser.m_assigned_store, &iter, TAG_COLUMN, &tag, -1 );
1985                                         TagBuilder.DeleteShaderTag( textureBrowser.shader.c_str(), tag );
1986                                         gtk_list_store_remove( textureBrowser.m_assigned_store, &iter );
1987                                 }
1988                         }
1989                 }
1990
1991                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1992
1993                 // Update the "available tags list"
1994                 BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
1995
1996                 // Save changes
1997                 TagBuilder.SaveXmlDoc();
1998         }
1999         g_slist_free( selected );
2000 }
2001
2002 void TextureBrowser_buildTagList(){
2003         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2004         textureBrowser.m_all_tags_list.clear();
2005
2006         std::set<CopiedString>::iterator iter;
2007
2008         for ( iter = textureBrowser.m_all_tags.begin(); iter != textureBrowser.m_all_tags.end(); ++iter )
2009         {
2010                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, (*iter).c_str());
2011         }
2012 }
2013
2014 void TextureBrowser_searchTags(){
2015         GSList* selected = NULL;
2016         GSList* node;
2017         gchar* tag;
2018         char buffer[256];
2019         char tags_searched[256];
2020         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2021
2022         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2023
2024         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2025
2026         if ( selected != NULL ) {
2027                 strcpy( buffer, "/root/*/*[tag='" );
2028                 strcpy( tags_searched, "[TAGS] " );
2029
2030                 for ( node = selected; node != NULL; node = node->next )
2031                 {
2032             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2033
2034                         if ( path ) {
2035                                 GtkTreeIter iter;
2036
2037                                 if ( gtk_tree_model_get_iter(textureBrowser.m_all_tags_list, &iter, path ) ) {
2038                                         gtk_tree_model_get(textureBrowser.m_all_tags_list, &iter, TAG_COLUMN, &tag, -1 );
2039
2040                                         strcat( buffer, tag );
2041                                         strcat( tags_searched, tag );
2042                                         if ( node != g_slist_last( node ) ) {
2043                                                 strcat( buffer, "' and tag='" );
2044                                                 strcat( tags_searched, ", " );
2045                                         }
2046                                 }
2047                         }
2048                 }
2049
2050                 strcat( buffer, "']" );
2051
2052                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2053
2054                 textureBrowser.m_found_shaders.clear(); // delete old list
2055                 TagBuilder.TagSearch( buffer, textureBrowser.m_found_shaders );
2056
2057                 if ( !textureBrowser.m_found_shaders.empty() ) { // found something
2058                         size_t shaders_found = textureBrowser.m_found_shaders.size();
2059
2060                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
2061                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
2062
2063                         std::set<CopiedString>::iterator iter;
2064
2065                         for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2066                         {
2067                                 std::string path = ( *iter ).c_str();
2068                                 size_t pos = path.find_last_of( "/", path.size() );
2069                                 std::string name = path.substr( pos + 1, path.size() );
2070                                 path = path.substr( 0, pos + 1 );
2071                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2072                         }
2073                 }
2074                 textureBrowser.m_searchedTags = true;
2075                 g_TextureBrowser_currentDirectory = tags_searched;
2076
2077                 textureBrowser.m_nTotalHeight = 0;
2078                 TextureBrowser_setOriginY( textureBrowser, 0 );
2079                 TextureBrowser_heightChanged( textureBrowser );
2080                 TextureBrowser_updateTitle();
2081         }
2082         g_slist_free( selected );
2083 }
2084
2085 void TextureBrowser_toggleSearchButton(){
2086         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2087         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ) );
2088
2089         if ( page == 0 ) { // tag page
2090                 gtk_widget_show_all( textureBrowser.m_search_button );
2091         }
2092         else {
2093                 textureBrowser.m_search_button.hide();
2094         }
2095 }
2096
2097 void TextureBrowser_constructTagNotebook(){
2098         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2099         textureBrowser.m_tag_notebook = ui::Widget::from(gtk_notebook_new());
2100         ui::Widget labelTags = ui::Label( "Tags" );
2101         ui::Widget labelTextures = ui::Label( "Textures" );
2102
2103         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tree, labelTextures );
2104         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tags, labelTags );
2105
2106         textureBrowser.m_tag_notebook.connect( "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
2107
2108         gtk_widget_show_all( textureBrowser.m_tag_notebook );
2109 }
2110
2111 void TextureBrowser_constructSearchButton(){
2112         auto image = ui::Widget::from(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
2113         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2114         textureBrowser.m_search_button = ui::Button(ui::New);
2115         textureBrowser.m_search_button.connect( "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
2116         gtk_widget_set_tooltip_text(textureBrowser.m_search_button, "Search with selected tags");
2117         textureBrowser.m_search_button.add(image);
2118 }
2119
2120 void TextureBrowser_checkTagFile(){
2121         const char SHADERTAG_FILE[] = "shadertags.xml";
2122         CopiedString default_filename, rc_filename;
2123         StringOutputStream stream( 256 );
2124         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2125
2126         stream << LocalRcPath_get();
2127         stream << SHADERTAG_FILE;
2128         rc_filename = stream.c_str();
2129
2130         if ( file_exists( rc_filename.c_str() ) ) {
2131                 textureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
2132
2133                 if ( textureBrowser.m_tags ) {
2134                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
2135                 }
2136         }
2137         else
2138         {
2139                 // load default tagfile
2140                 stream.clear();
2141                 stream << g_pGameDescription->mGameToolsPath.c_str();
2142                 stream << SHADERTAG_FILE;
2143                 default_filename = stream.c_str();
2144
2145                 if ( file_exists( default_filename.c_str() ) ) {
2146                         textureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
2147
2148                         if ( textureBrowser.m_tags ) {
2149                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
2150                         }
2151                 }
2152                 else
2153                 {
2154                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
2155                 }
2156         }
2157 }
2158
2159 void TextureBrowser_SetNotex(){
2160         IShader* notex = QERApp_Shader_ForName( DEFAULT_NOTEX_NAME );
2161         IShader* shadernotex = QERApp_Shader_ForName( DEFAULT_SHADERNOTEX_NAME );
2162
2163         g_notex = notex->getTexture()->name;
2164
2165         g_shadernotex = shadernotex->getTexture()->name;
2166
2167         notex->DecRef();
2168         shadernotex->DecRef();
2169 }
2170
2171 static bool isGLWidgetConstructed = false;
2172 static bool isWindowConstructed = false;
2173
2174 void TextureBrowser_constructGLWidget(){
2175         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2176         textureBrowser.m_gl_widget = glwidget_new( FALSE );
2177         g_object_ref( textureBrowser.m_gl_widget._handle );
2178
2179         gtk_widget_set_events( textureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
2180         gtk_widget_set_can_focus( textureBrowser.m_gl_widget, true );
2181
2182         textureBrowser.m_sizeHandler = textureBrowser.m_gl_widget.connect( "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &textureBrowser );
2183         textureBrowser.m_exposeHandler = textureBrowser.m_gl_widget.on_render( G_CALLBACK( TextureBrowser_expose ), &textureBrowser );
2184
2185         textureBrowser.m_gl_widget.connect( "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &textureBrowser );
2186         textureBrowser.m_gl_widget.connect( "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &textureBrowser );
2187         textureBrowser.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &textureBrowser );
2188         textureBrowser.m_gl_widget.connect( "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &textureBrowser );
2189
2190 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2191         textureBrowser.m_hframe.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2192 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2193         textureBrowser.m_frame.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2194 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2195
2196         textureBrowser.m_gl_widget.show();
2197
2198         isGLWidgetConstructed = true;
2199 }
2200
2201 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
2202         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
2203         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
2204         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
2205         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
2206         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2207
2208         TextureBrowser_checkTagFile();
2209         TextureBrowser_SetNotex();
2210
2211         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_activeShadersChanged>( textureBrowser ) );
2212
2213         textureBrowser.m_parent = toplevel;
2214
2215         auto table = ui::Table(3, 3, FALSE);
2216         auto vbox = ui::VBox(FALSE, 0);
2217         table.attach(vbox, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2218         vbox.show();
2219
2220         ui::Widget menu_bar{ui::null};
2221
2222         { // menu bar
2223                 menu_bar = ui::Widget::from(gtk_menu_bar_new());
2224                 auto menu_view = ui::Menu(ui::New);
2225                 auto view_item = TextureBrowser_constructViewMenu( menu_view );
2226                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2227                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2228
2229                 auto menu_tools = ui::Menu(ui::New);
2230                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2231                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2232                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2233
2234                 table.attach(menu_bar, {0, 3, 0, 1}, {GTK_FILL, GTK_SHRINK});
2235                 menu_bar.show();
2236         }
2237         { // Texture TreeView
2238                 textureBrowser.m_scr_win_tree = ui::ScrolledWindow(ui::New);
2239                 gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tree ), 0 );
2240
2241                 // vertical only scrolling for treeview
2242                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2243
2244                 textureBrowser.m_scr_win_tree.show();
2245
2246                 TextureBrowser_createTreeViewTree();
2247
2248                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), textureBrowser.m_treeViewTree  );
2249                 textureBrowser.m_treeViewTree.show();
2250         }
2251         { // gl_widget scrollbar
2252                 auto w = ui::Widget::from(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2253                 table.attach(w, {2, 3, 1, 2}, {GTK_SHRINK, GTK_FILL});
2254                 w.show();
2255                 textureBrowser.m_texture_scroll = w;
2256
2257                 auto vadjustment = ui::Adjustment::from(gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) ));
2258                 vadjustment.connect( "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &textureBrowser );
2259
2260                 textureBrowser.m_texture_scroll.visible(textureBrowser.m_showTextureScrollbar);
2261         }
2262         { // gl_widget
2263 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2264                 textureBrowser.m_vframe = ui::VBox( FALSE, 0 );
2265                 table.attach(textureBrowser.m_vframe, {1, 2, 1, 2});
2266
2267                 textureBrowser.m_vfiller = ui::VBox( FALSE, 0 );
2268                 textureBrowser.m_vframe.pack_start( textureBrowser.m_vfiller, FALSE, FALSE, 0 );
2269
2270                 textureBrowser.m_hframe = ui::HBox( FALSE, 0 );
2271                 textureBrowser.m_vframe.pack_start( textureBrowser.m_hframe, TRUE, TRUE, 0 );
2272
2273                 textureBrowser.m_hfiller = ui::HBox( FALSE, 0 );
2274                 textureBrowser.m_hframe.pack_start( textureBrowser.m_hfiller, FALSE, FALSE, 0 );
2275
2276                 textureBrowser.m_vframe.show();
2277                 textureBrowser.m_vfiller.show();
2278                 textureBrowser.m_hframe.show(),
2279                 textureBrowser.m_hfiller.show();
2280 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2281                 textureBrowser.m_frame = ui::VBox( FALSE, 0 );
2282                 table.attach(textureBrowser.m_frame, {1, 2, 1, 2});
2283                 textureBrowser.m_frame.show();
2284 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2285
2286                 TextureBrowser_constructGLWidget();
2287         }
2288
2289         // tag stuff
2290         if ( textureBrowser.m_tags ) {
2291                 { // fill tag GtkListStore
2292                         textureBrowser.m_all_tags_list = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2293             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_all_tags_list );
2294                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2295
2296                         TagBuilder.GetAllTags( textureBrowser.m_all_tags );
2297                         TextureBrowser_buildTagList();
2298                 }
2299                 { // tag menu bar
2300                         auto menu_tags = ui::Menu(ui::New);
2301                         auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2302                         gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2303                         gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2304                 }
2305                 { // Tag TreeView
2306                         textureBrowser.m_scr_win_tags = ui::ScrolledWindow(ui::New);
2307                         gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tags ), 0 );
2308
2309                         // vertical only scrolling for treeview
2310                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2311
2312                         TextureBrowser_createTreeViewTags();
2313
2314             auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2315                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2316
2317                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), textureBrowser.m_treeViewTags  );
2318                         textureBrowser.m_treeViewTags.show();
2319                 }
2320                 { // Texture/Tag notebook
2321                         TextureBrowser_constructTagNotebook();
2322                         vbox.pack_start( textureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2323                 }
2324                 { // Tag search button
2325                         TextureBrowser_constructSearchButton();
2326                         vbox.pack_end(textureBrowser.m_search_button, FALSE, FALSE, 0);
2327                 }
2328                 auto frame_table = ui::Table(3, 3, FALSE);
2329                 { // Tag frame
2330
2331                         textureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2332                         gtk_frame_set_label_align( GTK_FRAME( textureBrowser.m_tag_frame ), 0.5, 0.5 );
2333                         gtk_frame_set_shadow_type( GTK_FRAME( textureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2334
2335                         table.attach(textureBrowser.m_tag_frame, {1, 3, 2, 3}, {GTK_FILL, GTK_SHRINK});
2336
2337                         frame_table.show();
2338
2339                         textureBrowser.m_tag_frame.add(frame_table);
2340                 }
2341                 { // assigned tag list
2342                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2343                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2344                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2345
2346                         textureBrowser.m_assigned_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2347
2348             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_assigned_store );
2349                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2350
2351                         auto renderer = ui::CellRendererText(ui::New);
2352
2353                         textureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_assigned_store._handle));
2354                         textureBrowser.m_assigned_store.unref();
2355                         textureBrowser.m_assigned_tree.connect( "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2356                         gtk_tree_view_set_headers_visible(textureBrowser.m_assigned_tree, FALSE );
2357
2358             auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
2359                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2360
2361             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2362                         gtk_tree_view_append_column(textureBrowser.m_assigned_tree, column );
2363                         textureBrowser.m_assigned_tree.show();
2364
2365                         scrolled_win.show();
2366                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_assigned_tree  );
2367
2368                         frame_table.attach(scrolled_win, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2369                 }
2370                 { // available tag list
2371                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2372                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2373                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2374
2375                         textureBrowser.m_available_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2376             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_available_store );
2377                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2378
2379                         auto renderer = ui::CellRendererText(ui::New);
2380
2381                         textureBrowser.m_available_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_available_store._handle));
2382                         textureBrowser.m_available_store.unref();
2383                         textureBrowser.m_available_tree.connect( "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2384                         gtk_tree_view_set_headers_visible(textureBrowser.m_available_tree, FALSE );
2385
2386             auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2387                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2388
2389             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2390                         gtk_tree_view_append_column(textureBrowser.m_available_tree, column );
2391                         textureBrowser.m_available_tree.show();
2392
2393                         scrolled_win.show();
2394                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_available_tree  );
2395
2396                         frame_table.attach(scrolled_win, {2, 3, 1, 3}, {GTK_FILL, GTK_FILL});
2397                 }
2398                 { // tag arrow buttons
2399                         auto m_btn_left = ui::Button(ui::New);
2400                         auto m_btn_right = ui::Button(ui::New);
2401                         auto m_arrow_left = ui::Widget::from(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2402                         auto m_arrow_right = ui::Widget::from(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2403                         m_btn_left.add(m_arrow_left);
2404                         m_btn_right.add(m_arrow_right);
2405
2406                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2407                         m_arrow_left.dimensions(-1, 68);
2408                         m_arrow_right.dimensions(-1, 68);
2409
2410                         frame_table.attach(m_btn_left, {1, 2, 1, 2}, {GTK_SHRINK, GTK_EXPAND});
2411                         frame_table.attach(m_btn_right, {1, 2, 2, 3}, {GTK_SHRINK, GTK_EXPAND});
2412
2413                         m_btn_left.connect( "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2414                         m_btn_right.connect( "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2415
2416                         m_btn_left.show();
2417                         m_btn_right.show();
2418                         m_arrow_left.show();
2419                         m_arrow_right.show();
2420                 }
2421                 { // tag fram labels
2422                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2423                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2424
2425                         frame_table.attach(m_lbl_assigned, {0, 1, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2426                         frame_table.attach(m_lbl_unassigned, {2, 3, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2427
2428                         m_lbl_assigned.show();
2429                         m_lbl_unassigned.show();
2430                 }
2431         }
2432         else { // no tag support, show the texture tree only
2433                 vbox.pack_start( textureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2434         }
2435
2436         // TODO do we need this?
2437         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2438
2439         isWindowConstructed = true;
2440
2441         return table;
2442 }
2443
2444 void TextureBrowser_destroyGLWidget(){
2445         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2446         if ( isGLWidgetConstructed )
2447         {
2448                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_sizeHandler );
2449                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_exposeHandler );
2450
2451 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2452                 textureBrowser.m_hframe.remove( textureBrowser.m_gl_widget );
2453 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2454                 textureBrowser.m_frame.remove( textureBrowser.m_gl_widget );
2455 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2456
2457                 textureBrowser.m_gl_widget.unref();
2458
2459                 isGLWidgetConstructed = false;
2460         }
2461 }
2462
2463 void TextureBrowser_destroyWindow(){
2464         GlobalShaderSystem().setActiveShadersChangedNotify( Callback<void()>() );
2465
2466         TextureBrowser_destroyGLWidget();
2467 }
2468
2469 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2470 /* workaround for gtkglext on gtk 2 issue: OpenGL texture viewport being drawn over the other pages */
2471 /* this is very ugly: force the resizing of the viewport to a single bottom line by forcing the
2472  * resizing of the gl widget by expanding some empty boxes, so the widget area size is reduced
2473  * while covered by another page, so the texture viewport is still rendered over the other page
2474  * but does not annoy the user that much because it's just a line on the bottom that may even
2475  * be printed over existing bottom frame or very close to it. */
2476 void TextureBrowser_showGLWidget(){
2477         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2478         if ( isWindowConstructed && isGLWidgetConstructed )
2479         {
2480                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, FALSE, FALSE, 0, ui::Packing::START );
2481                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, TRUE, TRUE, 0, ui::Packing::START );
2482                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, FALSE, FALSE, 0, ui::Packing::START );
2483                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, TRUE, TRUE, 0, ui::Packing::START );
2484
2485                 textureBrowser.m_gl_widget.show();
2486 }
2487 }
2488
2489 void TextureBrowser_hideGLWidget(){
2490         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2491         if ( isWindowConstructed && isGLWidgetConstructed )
2492         {
2493                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, TRUE, TRUE, 0, ui::Packing::START);
2494                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, FALSE, FALSE, 0, ui::Packing::END );
2495                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, TRUE, TRUE, 0, ui::Packing::START);
2496                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, FALSE, FALSE, 0, ui::Packing::END );
2497
2498                 // The hack needs the GL widget to not be hidden to work,
2499                 // so resizing it triggers the redraw of it with the new size.
2500                 // GlobalTextureBrowser().m_gl_widget.hide();
2501
2502                 // Trigger the redraw.
2503                 TextureBrowser_redraw( &GlobalTextureBrowser() );
2504                 ui::process();
2505         }
2506 }
2507 #endif // WORKAROUND_MACOS_GTK2_GLWIDGET
2508
2509 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2510         return textureBrowser.color_textureback;
2511 }
2512
2513 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2514         textureBrowser.color_textureback = colour;
2515         TextureBrowser_queueDraw( textureBrowser );
2516 }
2517
2518 void TextureBrowser_selectionHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
2519         g_assert( selected != NULL );
2520
2521         gchar* name;
2522         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2523         *selected = g_slist_append( *selected, name );
2524 }
2525
2526 void TextureBrowser_shaderInfo(){
2527         const char* name = TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
2528         IShader* shader = QERApp_Shader_ForName( name );
2529
2530         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2531
2532         shader->DecRef();
2533 }
2534
2535 void TextureBrowser_addTag(){
2536         CopiedString tag;
2537         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2538
2539         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2540
2541         if ( result == eIDOK && !tag.empty() ) {
2542                 GtkTreeIter iter;
2543                 textureBrowser.m_all_tags.insert( tag.c_str() );
2544                 gtk_list_store_append( textureBrowser.m_available_store, &iter );
2545                 gtk_list_store_set( textureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2546
2547                 // Select the currently added tag in the available list
2548         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2549                 gtk_tree_selection_select_iter( selection, &iter );
2550
2551                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, tag.c_str());
2552         }
2553 }
2554
2555 void TextureBrowser_renameTag(){
2556         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2557            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2558            we need to count the number of selected rows first and use
2559            gtk_tree_selection_selected_foreach() then to go through the list of selected
2560            rows (which always containins a single row).
2561          */
2562
2563         GSList* selected = NULL;
2564         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2565
2566         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2567         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2568
2569         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2570                 CopiedString newTag;
2571                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2572
2573                 if ( result == eIDOK && !newTag.empty() ) {
2574                         GtkTreeIter iterList;
2575                         gchar* rowTag;
2576                         gchar* oldTag = (char*)selected->data;
2577
2578                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterList ) != 0;
2579
2580                         while ( row )
2581                         {
2582                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, &rowTag, -1 );
2583
2584                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2585                                         gtk_list_store_set( textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2586                                 }
2587                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterList ) != 0;
2588                         }
2589
2590                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2591
2592                         textureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2593                         textureBrowser.m_all_tags.insert( newTag );
2594
2595                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2596                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2597                 }
2598         }
2599         else
2600         {
2601                 ui::alert( textureBrowser.m_parent, "Select a single tag for renaming." );
2602         }
2603 }
2604
2605 void TextureBrowser_deleteTag(){
2606         GSList* selected = NULL;
2607         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2608
2609         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2610         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2611
2612         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2613                 auto result = ui::alert( textureBrowser.m_parent, "Are you sure you want to delete the selected tag?", "Delete Tag", ui::alert_type::YESNO, ui::alert_icon::Question );
2614
2615                 if ( result == ui::alert_response::YES ) {
2616                         GtkTreeIter iterSelected;
2617                         gchar *rowTag;
2618
2619                         gchar* tagSelected = (char*)selected->data;
2620
2621                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2622
2623                         while ( row )
2624                         {
2625                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterSelected, TAG_COLUMN, &rowTag, -1 );
2626
2627                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2628                                         gtk_list_store_remove( textureBrowser.m_all_tags_list, &iterSelected );
2629                                         break;
2630                                 }
2631                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2632                         }
2633
2634                         TagBuilder.DeleteTag( tagSelected );
2635                         textureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2636
2637                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2638                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2639                 }
2640         }
2641         else {
2642                 ui::alert( textureBrowser.m_parent, "Select a single tag for deletion." );
2643         }
2644 }
2645
2646 void TextureBrowser_copyTag(){
2647         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2648         textureBrowser.m_copied_tags.clear();
2649         TagBuilder.GetShaderTags( textureBrowser.shader.c_str(), textureBrowser.m_copied_tags );
2650 }
2651
2652 void TextureBrowser_pasteTag(){
2653         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2654         IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
2655         CopiedString shader = textureBrowser.shader.c_str();
2656
2657         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2658                 CopiedString shaderFile = ishader->getShaderFileName();
2659                 if ( shaderFile.empty() ) {
2660                         // it's a texture
2661                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2662                 }
2663                 else
2664                 {
2665                         // it's a shader
2666                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2667                 }
2668
2669                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2670                 {
2671                         TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2672                 }
2673         }
2674         else
2675         {
2676                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2677                 {
2678                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str() ) ) {
2679                                 // the tag doesn't exist - let's add it
2680                                 TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2681                         }
2682                 }
2683         }
2684
2685         ishader->DecRef();
2686
2687         TagBuilder.SaveXmlDoc();
2688         BuildStoreAssignedTags( textureBrowser.m_assigned_store, shader.c_str(), &textureBrowser );
2689         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2690 }
2691
2692 void TextureBrowser_RefreshShaders(){
2693         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2694         ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2695         GlobalShaderSystem().refresh();
2696         UpdateAllWindows();
2697     auto selection = gtk_tree_view_get_selection(GlobalTextureBrowser().m_treeViewTree);
2698         GtkTreeModel* model = NULL;
2699         GtkTreeIter iter;
2700         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2701         {
2702                 gchar dirName[1024];
2703
2704                 gchar* buffer;
2705                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2706                 strcpy( dirName, buffer );
2707                 g_free( buffer );
2708                 if ( !TextureBrowser_showWads() ) {
2709                         strcat( dirName, "/" );
2710                 }
2711                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2712                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2713         }
2714 }
2715
2716 void TextureBrowser_ToggleShowShaders(){
2717         GlobalTextureBrowser().m_showShaders ^= 1;
2718         GlobalTextureBrowser().m_showshaders_item.update();
2719         TextureBrowser_queueDraw( GlobalTextureBrowser() );
2720 }
2721
2722 void TextureBrowser_ToggleShowShaderListOnly(){
2723         g_TextureBrowser_shaderlistOnly ^= 1;
2724         GlobalTextureBrowser().m_showshaderlistonly_item.update();
2725
2726         TextureBrowser_constructTreeStore();
2727 }
2728
2729 void TextureBrowser_showAll(){
2730         g_TextureBrowser_currentDirectory = "";
2731         GlobalTextureBrowser().m_searchedTags = false;
2732         TextureBrowser_heightChanged( GlobalTextureBrowser() );
2733         TextureBrowser_updateTitle();
2734 }
2735
2736 void TextureBrowser_showUntagged(){
2737         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2738         auto result = ui::alert( textureBrowser.m_parent, "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", ui::alert_type::YESNO, ui::alert_icon::Warning );
2739
2740         if ( result == ui::alert_response::YES ) {
2741                 textureBrowser.m_found_shaders.clear();
2742                 TagBuilder.GetUntagged( textureBrowser.m_found_shaders );
2743                 std::set<CopiedString>::iterator iter;
2744
2745                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2746
2747                 for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2748                 {
2749                         std::string path = ( *iter ).c_str();
2750                         size_t pos = path.find_last_of( "/", path.size() );
2751                         std::string name = path.substr( pos + 1, path.size() );
2752                         path = path.substr( 0, pos + 1 );
2753                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2754                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2755                 }
2756
2757                 g_TextureBrowser_currentDirectory = "Untagged";
2758                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2759                 TextureBrowser_heightChanged( textureBrowser );
2760                 TextureBrowser_updateTitle();
2761         }
2762 }
2763
2764 void TextureBrowser_FixedSize(){
2765         g_TextureBrowser_fixedSize ^= 1;
2766         GlobalTextureBrowser().m_fixedsize_item.update();
2767         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2768 }
2769
2770 void TextureBrowser_FilterMissing(){
2771         g_TextureBrowser_filterMissing ^= 1;
2772         GlobalTextureBrowser().m_filternotex_item.update();
2773         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2774         TextureBrowser_RefreshShaders();
2775 }
2776
2777 void TextureBrowser_FilterFallback(){
2778         g_TextureBrowser_filterFallback ^= 1;
2779         GlobalTextureBrowser().m_hidenotex_item.update();
2780         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2781         TextureBrowser_RefreshShaders();
2782 }
2783
2784 void TextureBrowser_EnableAlpha(){
2785         g_TextureBrowser_enableAlpha ^= 1;
2786         GlobalTextureBrowser().m_enablealpha_item.update();
2787         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2788 }
2789
2790 void TextureBrowser_exportTitle( const Callback<void(const char *)> & importer ){
2791         StringOutputStream buffer( 64 );
2792         buffer << "Textures: ";
2793         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2794                 buffer << g_TextureBrowser_currentDirectory.c_str();
2795         }
2796         else
2797         {
2798                 buffer << "all";
2799         }
2800         importer( buffer.c_str() );
2801 }
2802
2803 struct TextureScale {
2804         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2805                 switch (self.m_textureScale) {
2806                         case 10:
2807                                 returnz(0);
2808                                 break;
2809                         case 25:
2810                                 returnz(1);
2811                                 break;
2812                         case 50:
2813                                 returnz(2);
2814                                 break;
2815                         case 100:
2816                                 returnz(3);
2817                                 break;
2818                         case 200:
2819                                 returnz(4);
2820                                 break;
2821                 }
2822         }
2823
2824         static void Import(TextureBrowser &self, int value) {
2825                 switch (value) {
2826                         case 0:
2827                                 TextureBrowser_setScale(self, 10);
2828                                 break;
2829                         case 1:
2830                                 TextureBrowser_setScale(self, 25);
2831                                 break;
2832                         case 2:
2833                                 TextureBrowser_setScale(self, 50);
2834                                 break;
2835                         case 3:
2836                                 TextureBrowser_setScale(self, 100);
2837                                 break;
2838                         case 4:
2839                                 TextureBrowser_setScale(self, 200);
2840                                 break;
2841                 }
2842         }
2843 };
2844
2845 struct UniformTextureSize {
2846         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2847                 returnz(GlobalTextureBrowser().m_uniformTextureSize);
2848         }
2849
2850         static void Import(TextureBrowser &self, int value) {
2851                 if (value > 16)
2852                         TextureBrowser_setUniformSize(self, value);
2853         }
2854 };
2855
2856 struct UniformTextureMinSize {
2857         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2858                 returnz(GlobalTextureBrowser().m_uniformTextureMinSize);
2859         }
2860
2861         static void Import(TextureBrowser &self, int value) {
2862                 if (value > 16)
2863                         TextureBrowser_setUniformSize(self, value);
2864         }
2865 };
2866
2867 void TextureBrowser_constructPreferences( PreferencesPage& page ){
2868         page.appendCheckBox(
2869                 "", "Texture scrollbar",
2870                 make_property<TextureBrowser_ShowScrollbar>(GlobalTextureBrowser())
2871                 );
2872         {
2873                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
2874                 page.appendCombo(
2875                         "Texture Thumbnail Scale",
2876                         STRING_ARRAY_RANGE( texture_scale ),
2877                         make_property<TextureScale>(GlobalTextureBrowser())
2878                         );
2879         }
2880         page.appendSpinner( "Thumbnails Max Size", GlobalTextureBrowser().m_uniformTextureSize, GlobalTextureBrowser().m_uniformTextureSize, 16, 8192 );
2881         page.appendSpinner( "Thumbnails Min Size", GlobalTextureBrowser().m_uniformTextureMinSize, GlobalTextureBrowser().m_uniformTextureMinSize, 16, 8192 );
2882         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
2883         {
2884                 const char* startup_shaders[] = { "None", TextureBrowser_getCommonShadersName() };
2885                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
2886         }
2887 }
2888
2889 void TextureBrowser_constructPage( PreferenceGroup& group ){
2890         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
2891         TextureBrowser_constructPreferences( page );
2892 }
2893
2894 void TextureBrowser_registerPreferencesPage(){
2895         PreferencesDialog_addSettingsPage( makeCallbackF(TextureBrowser_constructPage) );
2896 }
2897
2898
2899 #include "preferencesystem.h"
2900 #include "stringio.h"
2901
2902
2903 void TextureClipboard_textureSelected( const char* shader );
2904
2905 void TextureBrowser_Construct(){
2906         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2907
2908         GlobalCommands_insert( "ShaderInfo", makeCallbackF(TextureBrowser_shaderInfo) );
2909         GlobalCommands_insert( "ShowUntagged", makeCallbackF(TextureBrowser_showUntagged) );
2910         GlobalCommands_insert( "AddTag", makeCallbackF(TextureBrowser_addTag) );
2911         GlobalCommands_insert( "RenameTag", makeCallbackF(TextureBrowser_renameTag) );
2912         GlobalCommands_insert( "DeleteTag", makeCallbackF(TextureBrowser_deleteTag) );
2913         GlobalCommands_insert( "CopyTag", makeCallbackF(TextureBrowser_copyTag) );
2914         GlobalCommands_insert( "PasteTag", makeCallbackF(TextureBrowser_pasteTag) );
2915         GlobalCommands_insert( "RefreshShaders", makeCallbackF(VFS_Refresh) );
2916         GlobalToggles_insert( "ShowInUse", makeCallbackF(TextureBrowser_ToggleHideUnused), ToggleItem::AddCallbackCaller( textureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
2917         GlobalCommands_insert( "ShowAllTextures", makeCallbackF(TextureBrowser_showAll), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
2918         GlobalCommands_insert( "ToggleTextures", makeCallbackF(TextureBrowser_toggleShow), Accelerator( 'T' ) );
2919         GlobalToggles_insert( "ToggleShowShaders", makeCallbackF(TextureBrowser_ToggleShowShaders), ToggleItem::AddCallbackCaller( textureBrowser.m_showshaders_item ) );
2920         GlobalToggles_insert( "ToggleShowShaderlistOnly", makeCallbackF(TextureBrowser_ToggleShowShaderListOnly), ToggleItem::AddCallbackCaller( textureBrowser.m_showshaderlistonly_item ) );
2921         GlobalToggles_insert( "FixedSize", makeCallbackF(TextureBrowser_FixedSize), ToggleItem::AddCallbackCaller( textureBrowser.m_fixedsize_item ) );
2922         GlobalToggles_insert( "FilterMissing", makeCallbackF(TextureBrowser_FilterMissing), ToggleItem::AddCallbackCaller( textureBrowser.m_filternotex_item ) );
2923         GlobalToggles_insert( "FilterFallback", makeCallbackF(TextureBrowser_FilterFallback), ToggleItem::AddCallbackCaller( textureBrowser.m_hidenotex_item ) );
2924         GlobalToggles_insert( "EnableAlpha", makeCallbackF(TextureBrowser_EnableAlpha), ToggleItem::AddCallbackCaller( textureBrowser.m_enablealpha_item ) );
2925
2926         GlobalPreferenceSystem().registerPreference( "TextureScale", make_property_string<TextureScale>(textureBrowser) );
2927         GlobalPreferenceSystem().registerPreference( "UniformTextureSize", make_property_string<UniformTextureSize>(textureBrowser) );
2928         GlobalPreferenceSystem().registerPreference( "UniformTextureMinSize", make_property_string<UniformTextureMinSize>(textureBrowser) );
2929         GlobalPreferenceSystem().registerPreference( "TextureScrollbar", make_property_string<TextureBrowser_ShowScrollbar>(textureBrowser));
2930         GlobalPreferenceSystem().registerPreference( "ShowShaders", make_property_string( textureBrowser.m_showShaders ) );
2931         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", make_property_string( g_TextureBrowser_shaderlistOnly ) );
2932         GlobalPreferenceSystem().registerPreference( "FixedSize", make_property_string( g_TextureBrowser_fixedSize ) );
2933         GlobalPreferenceSystem().registerPreference( "FilterMissing", make_property_string( g_TextureBrowser_filterMissing ) );
2934         GlobalPreferenceSystem().registerPreference( "EnableAlpha", make_property_string( g_TextureBrowser_enableAlpha ) );
2935         GlobalPreferenceSystem().registerPreference( "LoadShaders", make_property_string( reinterpret_cast<int&>( textureBrowser.m_startupShaders ) ) );
2936         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", make_property_string( textureBrowser.m_mouseWheelScrollIncrement ) );
2937         GlobalPreferenceSystem().registerPreference( "SI_Colors0", make_property_string( textureBrowser.color_textureback ) );
2938
2939         textureBrowser.shader = texdef_name_default();
2940
2941         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw>( textureBrowser ) );
2942
2943         TextureBrowser_registerPreferencesPage();
2944
2945         GlobalShaderSystem().attach( g_ShadersObserver );
2946
2947         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
2948 }
2949
2950 void TextureBrowser_Destroy(){
2951         GlobalShaderSystem().detach( g_ShadersObserver );
2952
2953         Textures_setModeChangedNotify( Callback<void()>() );
2954 }
2955
2956 #if WORKAROUND_WINDOWS_GTK2_GLWIDGET
2957 ui::GLArea TextureBrowser_getGLWidget(){
2958         return GlobalTextureBrowser().m_gl_widget;
2959 }
2960 #endif // WORKAROUND_WINDOWS_GTK2_GLWIDGET