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