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