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