app_Main.py 484 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. # version = "Unstable Version"
  138. version = 8.994
  139. version_date = "2020/10/30"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, qapp, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # App Editors will be instantiated further below
  224. self.exc_editor = None
  225. self.grb_editor = None
  226. self.geo_editor = None
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.listen_th = QtCore.QThread()
  233. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.listen_th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # ########################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. if platform.architecture()[0] == '32bit':
  245. self.log.debug("Win32!")
  246. else:
  247. self.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. self.log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. self.log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. self.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = self.preprocessors_path()
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create tools_db.FlatDB file if there is none
  299. db_path = self.tools_database_path()
  300. try:
  301. f = open(db_path)
  302. f.close()
  303. except IOError:
  304. self.log.debug('Creating empty tools_db.FlatDB')
  305. f = open(db_path, 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create current_defaults.FlatConfig file if there is none
  309. def_path = self.defaults_path()
  310. try:
  311. f = open(def_path)
  312. f.close()
  313. except IOError:
  314. self.log.debug('Creating empty current_defaults.FlatConfig')
  315. f = open(def_path, 'w')
  316. json.dump({}, f)
  317. f.close()
  318. # the factory defaults are written only once at the first launch of the application after installation
  319. FlatCAMDefaults.save_factory_defaults(self.factory_defaults_path(), self.version)
  320. # create a recent files json file if there is none
  321. rec_f_path = self.recent_files_path()
  322. try:
  323. f = open(rec_f_path)
  324. f.close()
  325. except IOError:
  326. self.log.debug('Creating empty recent.json')
  327. f = open(rec_f_path, 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. rec_proj_path = self.recent_projects_path()
  332. try:
  333. fp = open(rec_proj_path)
  334. fp.close()
  335. except IOError:
  336. self.log.debug('Creating empty recent_projects.json')
  337. fp = open(rec_proj_path, 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. self.log.debug("Application path is " + self.app_home)
  344. self.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  353. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  354. if user_defaults:
  355. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  356. if self.defaults['units'] == 'MM':
  357. self.decimals = int(self.defaults['decimals_metric'])
  358. else:
  359. self.decimals = int(self.defaults['decimals_inch'])
  360. if self.defaults["global_gray_icons"] is False:
  361. self.resource_location = 'assets/resources'
  362. else:
  363. self.resource_location = 'assets/resources/dark_resources'
  364. self.current_units = self.defaults['units']
  365. # ###########################################################################################################
  366. # #################################### SETUP OBJECT CLASSES #################################################
  367. # ###########################################################################################################
  368. self.setup_obj_classes()
  369. # ###########################################################################################################
  370. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  371. # ###########################################################################################################
  372. self.pool = Pool()
  373. # ###########################################################################################################
  374. # ###################################### Clear GUI Settings - once at first start ###########################
  375. # ###########################################################################################################
  376. if self.defaults["first_run"] is True:
  377. # on first run clear the previous QSettings, therefore clearing the GUI settings
  378. qsettings = QSettings("Open Source", "FlatCAM")
  379. for key in qsettings.allKeys():
  380. qsettings.remove(key)
  381. # This will write the setting to the platform specific storage.
  382. del qsettings
  383. # ###########################################################################################################
  384. # ###################################### Setting the Splash Screen ##########################################
  385. # ###########################################################################################################
  386. splash_settings = QSettings("Open Source", "FlatCAM")
  387. if splash_settings.contains("splash_screen"):
  388. show_splash = splash_settings.value("splash_screen")
  389. else:
  390. splash_settings.setValue('splash_screen', 1)
  391. # This will write the setting to the platform specific storage.
  392. del splash_settings
  393. show_splash = 1
  394. if show_splash and self.cmd_line_headless != 1:
  395. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  396. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  397. # self.splash.setMask(splash_pix.mask())
  398. # move splashscreen to the current monitor
  399. desktop = QtWidgets.QApplication.desktop()
  400. screen = desktop.screenNumber(QtGui.QCursor.pos())
  401. current_screen_center = desktop.availableGeometry(screen).center()
  402. self.splash.move(current_screen_center - self.splash.rect().center())
  403. self.splash.show()
  404. self.splash.showMessage(_("The application is initializing ..."),
  405. alignment=Qt.AlignBottom | Qt.AlignLeft,
  406. color=QtGui.QColor("gray"))
  407. else:
  408. self.splash = None
  409. show_splash = 0
  410. # ###########################################################################################################
  411. # ######################################### Initialize GUI ##################################################
  412. # ###########################################################################################################
  413. # FlatCAM colors used in plotting
  414. self.FC_light_green = '#BBF268BF'
  415. self.FC_dark_green = '#006E20BF'
  416. self.FC_light_blue = '#a5a5ffbf'
  417. self.FC_dark_blue = '#0000ffbf'
  418. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  419. if theme_settings.contains("theme"):
  420. theme = theme_settings.value('theme', type=str)
  421. else:
  422. theme = 'white'
  423. if self.defaults["global_cursor_color_enabled"]:
  424. self.cursor_color_3D = self.defaults["global_cursor_color"]
  425. else:
  426. if theme == 'white':
  427. self.cursor_color_3D = 'black'
  428. else:
  429. self.cursor_color_3D = 'gray'
  430. # update the defaults dict with the setting in QSetting
  431. self.defaults['global_theme'] = theme
  432. self.ui = MainGUI(self)
  433. # set FlatCAM units in the Status bar
  434. self.set_screen_units(self.defaults['units'])
  435. # ###########################################################################################################
  436. # ########################################### AUTOSAVE SETUP ################################################
  437. # ###########################################################################################################
  438. self.block_autosave = False
  439. self.autosave_timer = QtCore.QTimer(self)
  440. self.save_project_auto_update()
  441. self.autosave_timer.timeout.connect(self.save_project_auto)
  442. # ###########################################################################################################
  443. # #################################### LOAD PREPROCESSORS ###################################################
  444. # ###########################################################################################################
  445. # ----------------------------------------- WARNING --------------------------------------------------------
  446. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  447. # That's because the number of preprocessors can vary and here the comboboxes are populated
  448. # -----------------------------------------------------------------------------------------------------------
  449. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  450. # the preprocessor file
  451. self.preprocessors = load_preprocessors(self)
  452. # make sure that always the 'default' preprocessor is the first item in the dictionary
  453. if 'default' in self.preprocessors.keys():
  454. new_ppp_dict = {}
  455. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  456. default_pp = self.preprocessors.pop('default')
  457. new_ppp_dict['default'] = default_pp
  458. # then add the rest of the keys
  459. for name, val_class in self.preprocessors.items():
  460. new_ppp_dict[name] = val_class
  461. # and now put back the ordered dict with 'default' key first
  462. self.preprocessors = new_ppp_dict
  463. # populate the Preprocessor ComboBoxes in the PREFERENCES
  464. for name in list(self.preprocessors.keys()):
  465. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  466. if name.partition('_')[0] == 'Paste':
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  468. continue
  469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  470. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  471. if name == 'hpgl':
  472. continue
  473. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  474. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  475. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  476. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  477. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  478. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  479. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  480. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  481. QtCore.Qt.ToolTipRole)
  482. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  483. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  484. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  485. QtCore.Qt.ToolTipRole)
  486. # ###########################################################################################################
  487. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  488. # ###########################################################################################################
  489. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  490. inform=self.inform)
  491. self.preferencesUiManager.defaults_write_form()
  492. # When the self.defaults dictionary changes will update the Preferences GUI forms
  493. self.defaults.set_change_callback(self.on_defaults_dict_change)
  494. # ###########################################################################################################
  495. # ############################################ Data #########################################################
  496. # ###########################################################################################################
  497. self.recent = []
  498. self.recent_projects = []
  499. self.clipboard = QtWidgets.QApplication.clipboard()
  500. self.project_filename = None
  501. self.toggle_units_ignore = False
  502. self.main_thread = QtWidgets.QApplication.instance().thread()
  503. # ###########################################################################################################
  504. # ########################################## LOAD LANGUAGES ################################################
  505. # ###########################################################################################################
  506. self.languages = fcTranslate.load_languages()
  507. for name in sorted(self.languages.values()):
  508. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  509. # ###########################################################################################################
  510. # ####################################### APPLY APP LANGUAGE ################################################
  511. # ###########################################################################################################
  512. ret_val = fcTranslate.apply_language('strings')
  513. if ret_val == "no language":
  514. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  515. self.log.debug("Could not find the Language files. The App strings are missing.")
  516. else:
  517. # make the current language the current selection on the language combobox
  518. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  519. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  520. # ###########################################################################################################
  521. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  522. # ###########################################################################################################
  523. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  524. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  525. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  526. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  527. self.defaults.propagate_defaults()
  528. # ###########################################################################################################
  529. # ######################################## UPDATE THE OPTIONS ###############################################
  530. # ###########################################################################################################
  531. self.options = LoudDict()
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Update the self.options from the self.defaults
  534. # The self.defaults holds the application defaults while the self.options holds the object defaults
  535. # -----------------------------------------------------------------------------------------------------------
  536. # Copy app defaults to project options
  537. for def_key, def_val in self.defaults.items():
  538. self.options[def_key] = deepcopy(def_val)
  539. self.preferencesUiManager.show_preferences_gui()
  540. # ### End of Data ####
  541. # ###########################################################################################################
  542. # #################################### SETUP OBJECT COLLECTION ##############################################
  543. # ###########################################################################################################
  544. self.collection = ObjectCollection(app=self)
  545. self.ui.project_tab_layout.addWidget(self.collection.view)
  546. self.app_obj = AppObject(app=self)
  547. # ### Adjust tabs width ## ##
  548. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  549. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  550. self.collection.view.setMinimumWidth(290)
  551. self.log.debug("Finished creating Object Collection.")
  552. # ###########################################################################################################
  553. # ######################################## SETUP Plot Area ##################################################
  554. # ###########################################################################################################
  555. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  556. if self.defaults["global_graphic_engine"] == '3D':
  557. self.is_legacy = False
  558. else:
  559. self.is_legacy = True
  560. # Event signals disconnect id holders
  561. self.mp = None
  562. self.mm = None
  563. self.mr = None
  564. self.mdc = None
  565. self.mp_zc = None
  566. self.kp = None
  567. # Matplotlib axis
  568. self.axes = None
  569. if show_splash:
  570. self.splash.showMessage(_("The application is initializing ...\n"
  571. "Canvas initialization started."),
  572. alignment=Qt.AlignBottom | Qt.AlignLeft,
  573. color=QtGui.QColor("gray"))
  574. start_plot_time = time.time() # debug
  575. self.plotcanvas = None
  576. self.app_cursor = None
  577. self.hover_shapes = None
  578. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  579. # setup the PlotCanvas
  580. self.on_plotcanvas_setup()
  581. end_plot_time = time.time()
  582. self.used_time = end_plot_time - start_plot_time
  583. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  584. if show_splash:
  585. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  586. "Canvas initialization started.\n"
  587. "Canvas initialization finished in"), '%.2f' % self.used_time),
  588. alignment=Qt.AlignBottom | Qt.AlignLeft,
  589. color=QtGui.QColor("gray"))
  590. self.ui.splitter.setStretchFactor(1, 2)
  591. # ###########################################################################################################
  592. # ############################################### Worker SETUP ##############################################
  593. # ###########################################################################################################
  594. if self.defaults["global_worker_number"]:
  595. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  596. else:
  597. self.workers = WorkerStack(workers_number=2)
  598. self.worker_task.connect(self.workers.add_task)
  599. self.log.debug("Finished creating Workers crew.")
  600. # ###########################################################################################################
  601. # ############################################# Activity Monitor ############################################
  602. # ###########################################################################################################
  603. # self.activity_view = FlatCAMActivityView(app=self)
  604. # self.ui.infobar.addWidget(self.activity_view)
  605. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  606. # ###########################################################################################################
  607. # ########################################## Other setups ###################################################
  608. # ###########################################################################################################
  609. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  610. # depending on from where those tools are called different actions can be done
  611. self.call_source = 'app'
  612. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  613. self.tool_tab_locked = False
  614. # decide if to show or hide the Notebook side of the screen at startup
  615. if self.defaults["global_project_at_startup"] is True:
  616. self.ui.splitter.setSizes([1, 1])
  617. else:
  618. self.ui.splitter.setSizes([0, 1])
  619. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  620. self.setup_default_properties_tab()
  621. # ###########################################################################################################
  622. # ####################################### Auto-complete KEYWORDS ############################################
  623. # ###########################################################################################################
  624. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  625. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  626. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  627. 'export_exc',
  628. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  629. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  630. 'interiors', 'isolate', 'join_excellon',
  631. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  632. 'mirror', 'ncc',
  633. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  634. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  635. 'options', 'origin',
  636. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  637. 'save', 'save_project',
  638. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  639. 'skew', 'subtract_poly', 'subtract_rectangle',
  640. 'version', 'write_gcode'
  641. ]
  642. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  643. 'Paste_1',
  644. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  645. 'Toolchange_manual', 'True', 'Users',
  646. 'all', 'auto', 'axis',
  647. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  648. 'contour', 'default',
  649. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  650. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  651. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  652. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  653. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  654. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  655. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  656. 'spacing_columns',
  657. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  658. 'toolchange_xy', 'toolchangez', 'travelz',
  659. 'tooldia', 'use_threads', 'value',
  660. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  661. ]
  662. self.tcl_keywords = [
  663. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  664. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  665. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  666. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  667. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  668. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  669. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  670. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  671. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  672. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  673. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  674. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  675. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  676. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  677. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  678. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  679. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  680. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  681. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  682. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  683. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  684. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  685. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  686. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  687. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  688. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  689. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  690. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  691. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  692. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  693. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  694. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  695. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  696. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  697. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  698. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  699. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  700. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  701. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  702. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  703. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  704. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  705. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  706. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  707. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  708. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  709. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  710. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  711. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  712. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  713. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  714. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  715. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  716. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  717. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  718. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  719. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  720. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  721. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  722. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  723. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  724. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  725. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  726. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  727. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  728. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  729. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  730. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  731. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  732. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  733. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  734. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  735. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  736. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  737. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  738. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  739. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  740. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  741. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  742. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  743. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  744. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  745. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  746. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  747. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  748. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  749. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  750. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  751. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  752. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  753. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  754. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  755. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  756. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  757. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  758. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  759. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  760. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  761. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  762. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  763. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  764. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  765. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  766. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  767. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  768. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  769. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  770. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  771. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  772. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  773. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  774. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  775. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  776. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  777. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  778. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  779. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  780. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  781. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  782. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  783. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  784. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  785. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  786. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  787. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  788. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  789. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  790. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  791. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  792. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  793. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  794. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  795. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  796. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  797. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  798. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  799. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  800. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  801. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  802. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  803. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  804. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  805. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  806. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  807. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  808. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  809. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  810. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  811. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  812. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  813. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  814. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  815. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  816. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  817. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  818. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  819. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  820. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  821. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  822. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  823. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  824. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  825. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  826. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  827. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  828. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  829. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  830. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  831. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  832. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  833. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  834. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  835. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  836. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  837. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  838. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  839. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  840. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  841. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  842. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  843. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  844. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  845. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  846. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  847. ]
  848. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  849. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  850. # ###########################################################################################################
  851. # ########################################## Tools and Plugins ##############################################
  852. # ###########################################################################################################
  853. self.shell = None
  854. self.dblsidedtool = None
  855. self.distance_tool = None
  856. self.distance_min_tool = None
  857. self.panelize_tool = None
  858. self.film_tool = None
  859. self.paste_tool = None
  860. self.calculator_tool = None
  861. self.rules_tool = None
  862. self.sub_tool = None
  863. self.move_tool = None
  864. self.cutout_tool = None
  865. self.ncclear_tool = None
  866. self.paint_tool = None
  867. self.isolation_tool = None
  868. self.drilling_tool = None
  869. self.optimal_tool = None
  870. self.transform_tool = None
  871. self.properties_tool = None
  872. self.pdf_tool = None
  873. self.image_tool = None
  874. self.pcb_wizard_tool = None
  875. self.cal_exc_tool = None
  876. self.qrcode_tool = None
  877. self.copper_thieving_tool = None
  878. self.fiducial_tool = None
  879. self.edrills_tool = None
  880. self.align_objects_tool = None
  881. self.punch_tool = None
  882. self.invert_tool = None
  883. self.corners_tool = None
  884. self.etch_tool = None
  885. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  886. try:
  887. self.install_tools()
  888. except AttributeError as e:
  889. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  890. # ###########################################################################################################
  891. # ######################################### BookMarks Manager ###############################################
  892. # ###########################################################################################################
  893. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  894. self.install_bookmarks()
  895. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  896. # ###########################################################################################################
  897. # ########################################### Tools Database ################################################
  898. # ###########################################################################################################
  899. self.tools_db_tab = None
  900. # ### System Font Parsing ###
  901. # self.f_parse = ParseFont(self)
  902. # self.parse_system_fonts()
  903. # ###########################################################################################################
  904. # ############################################## Shell SETUP ################################################
  905. # ###########################################################################################################
  906. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  907. if self.defaults["global_shell_at_startup"]:
  908. self.ui.shell_dock.show()
  909. else:
  910. self.ui.shell_dock.hide()
  911. # ###########################################################################################################
  912. # ######################################### Check for updates ###############################################
  913. # ###########################################################################################################
  914. # Separate thread (Not worker)
  915. # Check for updates on startup but only if the user consent and the app is not in Beta version
  916. if (self.beta is False or self.beta is None) and \
  917. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  918. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  919. # self.thr2 = QtCore.QThread()
  920. self.worker_task.emit({'fcn': self.version_check,
  921. 'params': []})
  922. # self.thr2.start(QtCore.QThread.LowPriority)
  923. # ###########################################################################################################
  924. # ##################################### Register files with FlatCAM; #######################################
  925. # ################################### It works only for Windows for now ####################################
  926. # ###########################################################################################################
  927. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  928. self.on_register_files()
  929. # ###########################################################################################################
  930. # ######################################## Variables for global usage #######################################
  931. # ###########################################################################################################
  932. # hold the App units
  933. self.units = 'MM'
  934. # coordinates for relative position display
  935. self.rel_point1 = (0, 0)
  936. self.rel_point2 = (0, 0)
  937. # variable to store coordinates
  938. self.pos = (0, 0)
  939. self.pos_canvas = (0, 0)
  940. self.pos_jump = (0, 0)
  941. # variable to store mouse coordinates
  942. self.mouse = [0, 0]
  943. # variable to store the delta positions on cavnas
  944. self.dx = 0
  945. self.dy = 0
  946. # decide if we have a double click or single click
  947. self.doubleclick = False
  948. # store here the is_dragging value
  949. self.event_is_dragging = False
  950. # variable to store if a command is active (then the var is not None) and which one it is
  951. self.command_active = None
  952. # variable to store the status of moving selection action
  953. # None value means that it's not an selection action
  954. # True value = a selection from left to right
  955. # False value = a selection from right to left
  956. self.selection_type = None
  957. # List to store the objects that are currently loaded in FlatCAM
  958. # This list is updated on each object creation or object delete
  959. self.all_objects_list = []
  960. self.objects_under_the_click_list = []
  961. # List to store the objects that are selected
  962. self.sel_objects_list = []
  963. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  964. self.key_modifiers = None
  965. # Variable to store the status of the code editor
  966. self.toggle_codeeditor = False
  967. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  968. self.click_noproject = False
  969. self.cursor = None
  970. # Variable to store the GCODE that was edited
  971. self.gcode_edited = ""
  972. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  973. self.old_state_of_tools_toolbar = False
  974. self.text_editor_tab = None
  975. # here store the color of a Tab text before it is changed so it can be restored in the future
  976. self.old_tab_text_color = None
  977. # reference for the self.ui.code_editor
  978. self.reference_code_editor = None
  979. self.script_code = ''
  980. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  981. self.tools_db_changed_flag = False
  982. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  983. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  984. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  985. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  986. 'tsm']
  987. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  988. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  989. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  990. 'sbp', 'tap', 'xpi']
  991. self.svg_list = ['svg']
  992. self.dxf_list = ['dxf']
  993. self.pdf_list = ['pdf']
  994. self.prj_list = ['flatprj']
  995. self.conf_list = ['flatconfig']
  996. # last used filters
  997. self.last_op_gerber_filter = None
  998. self.last_op_excellon_filter = None
  999. self.last_op_gcode_filter = None
  1000. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1001. # flag for polygons not cleared
  1002. self.poly_not_cleared = False
  1003. # VisPy visuals
  1004. self.isHovering = False
  1005. self.notHovering = True
  1006. # Window geometry
  1007. self.x_pos = None
  1008. self.y_pos = None
  1009. self.width = None
  1010. self.height = None
  1011. # when True, the app has to return from any thread
  1012. self.abort_flag = False
  1013. # set the value used in the Windows Title
  1014. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1015. # this holds a widget that is installed in the Plot Area when View Source option is used
  1016. self.source_editor_tab = None
  1017. self.pagesize = {}
  1018. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1019. # VisPy visuals
  1020. if self.is_legacy is False:
  1021. try:
  1022. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1023. except AttributeError:
  1024. self.tool_shapes = None
  1025. else:
  1026. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1027. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1028. # used in the delayed shutdown self.start_delayed_quit() method
  1029. self.save_timer = None
  1030. # ###########################################################################################################
  1031. # ################################## ADDING FlatCAM EDITORS section #########################################
  1032. # ###########################################################################################################
  1033. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1034. # at the first launch of the App , the editors will not be functional.
  1035. try:
  1036. self.geo_editor = AppGeoEditor(self)
  1037. except Exception as es:
  1038. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1039. try:
  1040. self.exc_editor = AppExcEditor(self)
  1041. except Exception as es:
  1042. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1043. try:
  1044. self.grb_editor = AppGerberEditor(self)
  1045. except Exception as es:
  1046. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1047. try:
  1048. self.gcode_editor = AppGCodeEditor(self)
  1049. except Exception as es:
  1050. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1051. self.log.debug("Finished adding FlatCAM Editor's.")
  1052. self.ui.set_ui_title(name=_("New Project - Not saved"))
  1053. # ###########################################################################################################
  1054. # ########################################## Install OPTIMIZATIONS for GCode generation #####################
  1055. # ###########################################################################################################
  1056. current_platform = platform.architecture()[0]
  1057. if current_platform != '64bit':
  1058. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1059. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1060. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1061. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1062. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1063. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1064. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1065. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1066. # ###########################################################################################################
  1067. # ########################################### EXCLUSION AREAS ###############################################
  1068. # ###########################################################################################################
  1069. self.exc_areas = ExclusionAreas(app=self)
  1070. # ###########################################################################################################
  1071. # ###########################################################################################################
  1072. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1073. # ###########################################################################################################
  1074. # ###########################################################################################################
  1075. self.f_handlers = MenuFileHandlers(app=self)
  1076. # this is calculated in the class above (somehow?)
  1077. self.defaults["root_folder_path"] = self.app_home
  1078. # ###########################################################################################################
  1079. # ##################################### FIRST RUN SECTION ###################################################
  1080. # ################################ It's done only once after install #####################################
  1081. # ###########################################################################################################
  1082. if self.defaults["first_run"] is True:
  1083. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  1084. self.log.debug("-> First Run: Setting up the first Layout")
  1085. initial_lay = 'minimal'
  1086. self.on_layout(lay=initial_lay)
  1087. # Set the combobox in Preferences to the current layout
  1088. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1089. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1090. # after the first run, this object should be False
  1091. self.defaults["first_run"] = False
  1092. self.log.debug("-> First Run: Updating the Defaults file with Factory Defaults")
  1093. self.preferencesUiManager.save_defaults(silent=True)
  1094. # ###########################################################################################################
  1095. # ############################################### SYS TRAY ##################################################
  1096. # ###########################################################################################################
  1097. if self.defaults["global_systray_icon"]:
  1098. self.parent_w = QtWidgets.QWidget()
  1099. if self.cmd_line_headless == 1:
  1100. self.trayIcon = FlatCAMSystemTray(app=self,
  1101. icon=QtGui.QIcon(self.resource_location +
  1102. '/flatcam_icon32_green.png'),
  1103. headless=True,
  1104. parent=self.parent_w)
  1105. else:
  1106. self.trayIcon = FlatCAMSystemTray(app=self,
  1107. icon=QtGui.QIcon(self.resource_location +
  1108. '/flatcam_icon32_green.png'),
  1109. parent=self.parent_w)
  1110. # ###########################################################################################################
  1111. # ############################################ SETUP RECENT ITEMS ###########################################
  1112. # ###########################################################################################################
  1113. self.setup_recent_items()
  1114. # ###########################################################################################################
  1115. # ###########################################################################################################
  1116. # ############################################# Signal handling #############################################
  1117. # ###########################################################################################################
  1118. # ###########################################################################################################
  1119. # ########################################## Custom signals ################################################
  1120. # signal for displaying messages in status bar
  1121. self.inform[str].connect(self.info)
  1122. self.inform[str, bool].connect(self.info)
  1123. # signal for displaying messages in the shell
  1124. self.inform_shell[str].connect(self.info_shell)
  1125. self.inform_shell[str, bool].connect(self.info_shell)
  1126. # signal to be called when the app is quiting
  1127. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1128. self.message.connect(lambda: message_dialog(parent=self.ui))
  1129. # self.progress.connect(self.set_progress_bar)
  1130. # signals emitted when file state change
  1131. self.file_opened.connect(self.register_recent)
  1132. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1133. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1134. # when the defaults dictionary values change
  1135. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1136. # ########################################## Standard signals ###############################################
  1137. # ### Menu
  1138. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1139. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1140. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1141. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1142. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1143. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1144. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1145. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1146. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1147. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1148. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1149. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1150. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1151. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1152. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1153. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1154. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1155. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1156. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1157. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1158. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1159. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1160. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1161. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1162. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1163. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1164. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1165. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1166. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1167. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1168. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1169. self.ui.menufile_exit.triggered.connect(self.final_save)
  1170. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1171. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1172. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1173. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1174. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1175. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1176. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1177. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1178. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1179. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1180. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1181. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1182. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1183. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1184. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1185. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1186. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1187. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1188. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1189. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1190. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1191. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1192. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1193. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1194. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1195. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1196. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1197. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1198. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1199. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1200. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1201. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1202. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1203. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1204. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1205. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1206. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1207. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1208. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1209. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1210. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1211. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1212. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1213. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1214. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1215. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1216. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1217. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1218. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1219. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1220. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1221. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1222. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1223. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1224. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1225. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1226. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1227. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1228. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1229. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1230. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1231. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1232. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1233. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1234. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1235. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1236. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1237. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1238. # ToolBar signals
  1239. self.connect_toolbar_signals()
  1240. # Context Menu
  1241. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1242. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1243. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1244. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1245. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1246. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1247. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1248. self.ui.clearplot.triggered.connect(self.clear_plots)
  1249. self.ui.replot.triggered.connect(self.plot_all)
  1250. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1251. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1252. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1253. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1254. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1255. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1256. # Project Context Menu -> Color Setting
  1257. for act in self.ui.menuprojectcolor.actions():
  1258. act.triggered.connect(self.on_set_color_action_triggered)
  1259. # Notebook tab clicking
  1260. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1261. # ###########################################################################################################
  1262. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1263. # ###########################################################################################################
  1264. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1265. lambda: self.on_toggle_units(no_pref=False))
  1266. # ##################################### Workspace Setting Signals ###########################################
  1267. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1268. self.on_workspace_modified)
  1269. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1270. self.on_workspace_modified
  1271. )
  1272. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1273. # ###########################################################################################################
  1274. # ######################################## GUI SETTINGS SIGNALS #############################################
  1275. # ###########################################################################################################
  1276. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1277. # ######################################## Tools related signals ############################################
  1278. # portability changed signal
  1279. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1280. # Object list
  1281. self.object_status_changed.connect(self.collection.on_collection_updated)
  1282. # when there are arguments at application startup this get launched
  1283. self.args_at_startup[list].connect(self.on_startup_args)
  1284. # ###########################################################################################################
  1285. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1286. # ###########################################################################################################
  1287. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1288. lambda: self.restore_extensions(ext_type='excellon'))
  1289. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1290. lambda: self.restore_extensions(ext_type='gcode'))
  1291. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1292. lambda: self.restore_extensions(ext_type='gerber'))
  1293. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1294. lambda: self.delete_all_extensions(ext_type='excellon'))
  1295. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1296. lambda: self.delete_all_extensions(ext_type='gcode'))
  1297. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1298. lambda: self.delete_all_extensions(ext_type='gerber'))
  1299. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1300. lambda: self.add_extension(ext_type='excellon'))
  1301. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1302. lambda: self.add_extension(ext_type='gcode'))
  1303. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1304. lambda: self.add_extension(ext_type='gerber'))
  1305. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1306. lambda: self.del_extension(ext_type='excellon'))
  1307. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1308. lambda: self.del_extension(ext_type='gcode'))
  1309. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1310. lambda: self.del_extension(ext_type='gerber'))
  1311. # connect the 'Apply' buttons from the Preferences/File Associations
  1312. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1313. lambda: self.on_register_files(obj_type='excellon'))
  1314. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1315. lambda: self.on_register_files(obj_type='gcode'))
  1316. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1317. lambda: self.on_register_files(obj_type='gerber'))
  1318. # ###########################################################################################################
  1319. # ########################################### KEYWORDS SIGNALS ##############################################
  1320. # ###########################################################################################################
  1321. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1322. lambda: self.restore_extensions(ext_type='keyword'))
  1323. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1324. lambda: self.delete_all_extensions(ext_type='keyword'))
  1325. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1326. lambda: self.add_extension(ext_type='keyword'))
  1327. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1328. lambda: self.del_extension(ext_type='keyword'))
  1329. # ###########################################################################################################
  1330. # ########################################### GUI SIGNALS ###################################################
  1331. # ###########################################################################################################
  1332. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1333. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1334. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1335. # ###########################################################################################################
  1336. # ####################################### VARIOUS SIGNALS ###################################################
  1337. # ###########################################################################################################
  1338. # connect the abort_all_tasks related slots to the related signals
  1339. self.proc_container.idle_flag.connect(self.app_is_idle)
  1340. # signal emitted when a tab is closed in the Plot Area
  1341. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1342. # signal to close the application
  1343. self.close_app_signal.connect(self.kill_app)
  1344. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1345. # ###########################################################################################################
  1346. # ###########################################################################################################
  1347. # ###########################################################################################################
  1348. self.log.debug("Finished connecting Signals.")
  1349. # ###########################################################################################################
  1350. # ##################################### Finished the CONSTRUCTOR ############################################
  1351. # ###########################################################################################################
  1352. self.log.debug("END of constructor. Releasing control.")
  1353. # ###########################################################################################################
  1354. # ########################################## SHOW GUI #######################################################
  1355. # ###########################################################################################################
  1356. # if the app is not started as headless, show it
  1357. if self.cmd_line_headless != 1:
  1358. if show_splash:
  1359. # finish the splash
  1360. self.splash.finish(self.ui)
  1361. mgui_settings = QSettings("Open Source", "FlatCAM")
  1362. if mgui_settings.contains("maximized_gui"):
  1363. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1364. if maximized_ui is True:
  1365. self.ui.showMaximized()
  1366. else:
  1367. self.ui.show()
  1368. else:
  1369. self.ui.show()
  1370. if self.defaults["global_systray_icon"]:
  1371. self.trayIcon.show()
  1372. else:
  1373. log.warning("******************* RUNNING HEADLESS *******************")
  1374. # ###########################################################################################################
  1375. # ######################################## START-UP ARGUMENTS ###############################################
  1376. # ###########################################################################################################
  1377. # test if the program was started with a script as parameter
  1378. if self.cmd_line_shellvar:
  1379. try:
  1380. cnt = 0
  1381. command_tcl = 0
  1382. for i in self.cmd_line_shellvar.split(','):
  1383. if i is not None:
  1384. # noinspection PyBroadException
  1385. try:
  1386. command_tcl = eval(i)
  1387. except Exception:
  1388. command_tcl = i
  1389. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1390. cnt += 1
  1391. # if there are Windows paths then replace the path separator with a Unix like one
  1392. if sys.platform == 'win32':
  1393. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1394. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1395. except Exception as ext:
  1396. print("ERROR: ", ext)
  1397. sys.exit(2)
  1398. if self.cmd_line_shellfile:
  1399. if self.cmd_line_headless != 1:
  1400. if self.ui.shell_dock.isHidden():
  1401. self.ui.shell_dock.show()
  1402. try:
  1403. with open(self.cmd_line_shellfile, "r") as myfile:
  1404. # if show_splash:
  1405. # self.splash.showMessage('%s: %ssec\n%s' % (
  1406. # _("Canvas initialization started.\n"
  1407. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1408. # _("Executing Tcl Script ...")),
  1409. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1410. # color=QtGui.QColor("gray"))
  1411. cmd_line_shellfile_text = myfile.read()
  1412. if self.cmd_line_headless != 1:
  1413. self.shell.exec_command(cmd_line_shellfile_text)
  1414. else:
  1415. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1416. except Exception as ext:
  1417. print("ERROR: ", ext)
  1418. sys.exit(2)
  1419. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1420. # the path/file_name must be enclosed in quotes if it contain spaces
  1421. if App.args:
  1422. self.args_at_startup.emit(App.args)
  1423. if self.defaults.old_defaults_found is True:
  1424. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1425. "Please reboot the application to update."))
  1426. self.defaults.old_defaults_found = False
  1427. # ######################################### INIT FINISHED #######################################################
  1428. # #################################################################################################################
  1429. # #################################################################################################################
  1430. # #################################################################################################################
  1431. # #################################################################################################################
  1432. # #################################################################################################################
  1433. @staticmethod
  1434. def copy_and_overwrite(from_path, to_path):
  1435. """
  1436. From here:
  1437. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1438. :param from_path: source path
  1439. :param to_path: destination path
  1440. :return: None
  1441. """
  1442. if os.path.exists(to_path):
  1443. shutil.rmtree(to_path)
  1444. try:
  1445. shutil.copytree(from_path, to_path)
  1446. except FileNotFoundError:
  1447. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1448. shutil.copytree(from_new_path, to_path)
  1449. def on_startup_args(self, args, silent=False):
  1450. """
  1451. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1452. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1453. :param args: a list containing the application args at startup
  1454. :return: None
  1455. """
  1456. if args is not None:
  1457. args_to_process = args
  1458. else:
  1459. args_to_process = App.args
  1460. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1461. for argument in args_to_process:
  1462. if '.FlatPrj'.lower() in argument.lower():
  1463. try:
  1464. project_name = str(argument)
  1465. if project_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Cancelled."))
  1468. else:
  1469. # self.open_project(project_name)
  1470. run_from_arg = True
  1471. # self.worker_task.emit({'fcn': self.open_project,
  1472. # 'params': [project_name, run_from_arg]})
  1473. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1474. except Exception as e:
  1475. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1476. elif '.FlatConfig'.lower() in argument.lower():
  1477. try:
  1478. file_name = str(argument)
  1479. if file_name == "":
  1480. if silent is False:
  1481. self.inform.emit(_("Open Config file failed."))
  1482. else:
  1483. run_from_arg = True
  1484. # self.worker_task.emit({'fcn': self.open_config_file,
  1485. # 'params': [file_name, run_from_arg]})
  1486. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1487. except Exception as e:
  1488. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1489. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1490. try:
  1491. file_name = str(argument)
  1492. if file_name == "":
  1493. if silent is False:
  1494. self.inform.emit(_("Open Script file failed."))
  1495. else:
  1496. if silent is False:
  1497. self.on_fileopenscript(name=file_name)
  1498. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1499. self.on_filerunscript(name=file_name)
  1500. except Exception as e:
  1501. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1502. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1503. self.log.debug("App.on_startup_args() --> Quit event.")
  1504. sys.exit()
  1505. elif 'save'.lower() in argument.lower():
  1506. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1507. self.preferencesUiManager.save_defaults()
  1508. else:
  1509. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1510. proc_arg = argument.lower()
  1511. for ext in exc_list:
  1512. proc_ext = ext.replace(' ', '')
  1513. proc_ext = '.%s' % proc_ext
  1514. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1515. file_name = str(argument)
  1516. if file_name == "":
  1517. if silent is False:
  1518. self.inform.emit(_("Open Excellon file failed."))
  1519. else:
  1520. self.on_fileopenexcellon(name=file_name, signal=None)
  1521. return
  1522. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1523. for ext in gco_list:
  1524. proc_ext = ext.replace(' ', '')
  1525. proc_ext = '.%s' % proc_ext
  1526. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1527. file_name = str(argument)
  1528. if file_name == "":
  1529. if silent is False:
  1530. self.inform.emit(_("Open GCode file failed."))
  1531. else:
  1532. self.on_fileopengcode(name=file_name, signal=None)
  1533. return
  1534. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1535. for ext in grb_list:
  1536. proc_ext = ext.replace(' ', '')
  1537. proc_ext = '.%s' % proc_ext
  1538. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1539. file_name = str(argument)
  1540. if file_name == "":
  1541. if silent is False:
  1542. self.inform.emit(_("Open Gerber file failed."))
  1543. else:
  1544. self.on_fileopengerber(name=file_name, signal=None)
  1545. return
  1546. # if it reached here without already returning then the app was registered with a file that it does not
  1547. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1548. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1549. # for arg in args_to_process:
  1550. # if 'FlatCAM.exe' in arg:
  1551. # continue
  1552. # else:
  1553. # sys.exit(2)
  1554. def tools_database_path(self):
  1555. return os.path.join(self.data_path, 'tools_db.FlatDB')
  1556. def defaults_path(self):
  1557. return os.path.join(self.data_path, 'current_defaults.FlatConfig')
  1558. def factory_defaults_path(self):
  1559. return os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  1560. def recent_files_path(self):
  1561. return os.path.join(self.data_path, 'recent.json')
  1562. def recent_projects_path(self):
  1563. return os.path.join(self.data_path, 'recent_projects.json')
  1564. def preprocessors_path(self):
  1565. return os.path.join(self.data_path, 'preprocessors')
  1566. def on_app_restart(self):
  1567. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1568. # be left in the SySTray
  1569. try:
  1570. self.trayIcon.hide()
  1571. except Exception:
  1572. pass
  1573. fcTranslate.restart_program(app=self)
  1574. def clear_pool(self):
  1575. """
  1576. Clear the multiprocessing pool and calls garbage collector.
  1577. :return: None
  1578. """
  1579. self.pool.close()
  1580. self.pool = Pool()
  1581. self.pool_recreated.emit(self.pool)
  1582. gc.collect()
  1583. def install_tools(self):
  1584. """
  1585. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1586. Instantiation of the Tools classes.
  1587. The order that the tools are installed is important as they can depend on each other install position.
  1588. :return: None
  1589. """
  1590. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1591. self.shell = FCShell(app=self, version=self.version)
  1592. self.distance_tool = Distance(self)
  1593. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1594. before=self.ui.menueditorigin,
  1595. separator=False)
  1596. self.distance_min_tool = DistanceMin(self)
  1597. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1598. pos=self.ui.menuedit,
  1599. before=self.ui.menueditorigin,
  1600. separator=True)
  1601. self.dblsidedtool = DblSidedTool(self)
  1602. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1603. self.cal_exc_tool = ToolCalibration(self)
  1604. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1605. before=self.dblsidedtool.menuAction,
  1606. separator=False)
  1607. self.align_objects_tool = AlignObjects(self)
  1608. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1609. self.edrills_tool = ToolExtractDrills(self)
  1610. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1611. self.panelize_tool = Panelize(self)
  1612. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1613. self.film_tool = Film(self)
  1614. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1615. self.paste_tool = SolderPaste(self)
  1616. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1617. self.calculator_tool = ToolCalculator(self)
  1618. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1619. self.sub_tool = ToolSub(self)
  1620. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1621. pos=self.ui.menutool, separator=True)
  1622. self.rules_tool = RulesCheck(self)
  1623. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1624. pos=self.ui.menutool, separator=False)
  1625. self.optimal_tool = ToolOptimal(self)
  1626. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1627. pos=self.ui.menutool, separator=True)
  1628. self.move_tool = ToolMove(self)
  1629. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1630. before=self.ui.menueditorigin, separator=True)
  1631. self.cutout_tool = CutOut(self)
  1632. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1633. before=self.sub_tool.menuAction)
  1634. self.ncclear_tool = NonCopperClear(self)
  1635. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1636. before=self.sub_tool.menuAction, separator=True)
  1637. self.paint_tool = ToolPaint(self)
  1638. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1639. before=self.sub_tool.menuAction, separator=True)
  1640. self.isolation_tool = ToolIsolation(self)
  1641. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1642. before=self.sub_tool.menuAction, separator=True)
  1643. self.drilling_tool = ToolDrilling(self)
  1644. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1645. before=self.sub_tool.menuAction, separator=True)
  1646. self.copper_thieving_tool = ToolCopperThieving(self)
  1647. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1648. pos=self.ui.menutool)
  1649. self.fiducial_tool = ToolFiducials(self)
  1650. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1651. pos=self.ui.menutool)
  1652. self.qrcode_tool = QRCode(self)
  1653. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1654. pos=self.ui.menutool)
  1655. self.punch_tool = ToolPunchGerber(self)
  1656. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1657. self.invert_tool = ToolInvertGerber(self)
  1658. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1659. self.corners_tool = ToolCorners(self)
  1660. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1661. self.etch_tool = ToolEtchCompensation(self)
  1662. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1663. self.transform_tool = ToolTransform(self)
  1664. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1665. pos=self.ui.menuoptions, separator=True)
  1666. self.properties_tool = Properties(self)
  1667. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1668. pos=self.ui.menuoptions)
  1669. self.pdf_tool = ToolPDF(self)
  1670. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1671. pos=self.ui.menufileimport,
  1672. separator=True)
  1673. self.image_tool = ToolImage(self)
  1674. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1675. pos=self.ui.menufileimport,
  1676. separator=True)
  1677. self.pcb_wizard_tool = PcbWizard(self)
  1678. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1679. pos=self.ui.menufileimport)
  1680. self.log.debug("Tools are installed.")
  1681. def remove_tools(self):
  1682. """
  1683. Will remove all the actions in the Tool menu.
  1684. :return: None
  1685. """
  1686. for act in self.ui.menutool.actions():
  1687. self.ui.menutool.removeAction(act)
  1688. def init_tools(self):
  1689. """
  1690. Initialize the Tool tab in the notebook side of the central widget.
  1691. Remove the actions in the Tools menu.
  1692. Instantiate again the FlatCAM tools (plugins).
  1693. All this is required when changing the layout: standard, compact etc.
  1694. :return: None
  1695. """
  1696. self.log.debug("init_tools()")
  1697. # delete the data currently in the Tools Tab and the Tab itself
  1698. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1699. if widget is not None:
  1700. widget.deleteLater()
  1701. self.ui.notebook.removeTab(2)
  1702. # rebuild the Tools Tab
  1703. self.ui.tool_tab = QtWidgets.QWidget()
  1704. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1705. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1706. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1707. self.ui.tool_scroll_area = VerticalScrollArea()
  1708. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1709. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1710. # first remove all of them
  1711. self.remove_tools()
  1712. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1713. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1714. '&Command Line\tS')
  1715. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1716. # third install all of them
  1717. try:
  1718. self.install_tools()
  1719. except AttributeError:
  1720. pass
  1721. self.log.debug("Tools are initialized.")
  1722. # def parse_system_fonts(self):
  1723. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1724. # 'params': []})
  1725. def connect_tools_signals_to_toolbar(self):
  1726. self.log.debug(" -> Connecting Tools Toolbar Signals")
  1727. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1728. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1729. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1730. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1731. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1732. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1733. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1734. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1735. self.ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1736. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1737. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1738. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1739. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1740. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1741. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1742. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1743. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1744. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1745. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1746. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1747. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1748. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1749. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1750. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1751. def connect_editors_toolbar_signals(self):
  1752. self.log.debug(" -> Connecting Editors Toolbar Signals")
  1753. # Geometry Editor Toolbar Signals
  1754. self.geo_editor.connect_geo_toolbar_signals()
  1755. # Gerber Editor Toolbar Signals
  1756. self.grb_editor.connect_grb_toolbar_signals()
  1757. # Excellon Editor Toolbar Signals
  1758. self.exc_editor.connect_exc_toolbar_signals()
  1759. def connect_toolbar_signals(self):
  1760. """
  1761. Reconnect the signals to the actions in the toolbar.
  1762. This has to be done each time after the FlatCAM tools are removed/installed.
  1763. :return: None
  1764. """
  1765. self.log.debug(" -> Connecting Toolbar Signals")
  1766. # Toolbar
  1767. # File Toolbar Signals
  1768. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1769. self.ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1770. self.ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1771. self.ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1772. self.ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1773. # View Toolbar Signals
  1774. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1775. self.ui.replot_btn.triggered.connect(self.plot_all)
  1776. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1777. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1778. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1779. # Edit Toolbar Signals
  1780. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1781. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1782. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1783. self.ui.delete_btn.triggered.connect(self.on_delete)
  1784. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1785. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1786. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1787. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1788. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1789. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1790. # Scripting Toolbar Signals
  1791. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1792. self.ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1793. self.ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1794. self.ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1795. # Tools Toolbar Signals
  1796. try:
  1797. self.connect_tools_signals_to_toolbar()
  1798. except Exception as err:
  1799. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1800. def on_layout(self, index=None, lay=None):
  1801. """
  1802. Set the toolbars layout (location)
  1803. :param index:
  1804. :param lay: Type of layout to be set on the toolbard
  1805. :return: None
  1806. """
  1807. self.defaults.report_usage("on_layout()")
  1808. self.log.debug(" ---> New Layout")
  1809. if lay:
  1810. current_layout = lay
  1811. else:
  1812. current_layout = self.ui.general_defaults_form.general_gui_group.layout_combo.get_value()
  1813. lay_settings = QSettings("Open Source", "FlatCAM")
  1814. lay_settings.setValue('layout', current_layout)
  1815. # This will write the setting to the platform specific storage.
  1816. del lay_settings
  1817. # first remove the toolbars:
  1818. self.log.debug(" -> Remove Toolbars")
  1819. try:
  1820. self.ui.removeToolBar(self.ui.toolbarfile)
  1821. self.ui.removeToolBar(self.ui.toolbaredit)
  1822. self.ui.removeToolBar(self.ui.toolbarview)
  1823. self.ui.removeToolBar(self.ui.toolbarshell)
  1824. self.ui.removeToolBar(self.ui.toolbartools)
  1825. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  1826. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  1827. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  1828. self.ui.removeToolBar(self.ui.toolbarshell)
  1829. except Exception:
  1830. pass
  1831. self.log.debug(" -> Add New Toolbars")
  1832. if current_layout == 'compact':
  1833. # ## TOOLBAR INSTALLATION # ##
  1834. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  1835. self.ui.toolbarfile.setObjectName('File_TB')
  1836. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  1837. self.ui.toolbaredit = QtWidgets.QToolBar('Edit Toolbar')
  1838. self.ui.toolbaredit.setObjectName('Edit_TB')
  1839. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbaredit)
  1840. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  1841. self.ui.toolbarshell.setObjectName('Shell_TB')
  1842. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  1843. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  1844. self.ui.toolbartools.setObjectName('Tools_TB')
  1845. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  1846. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  1847. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  1848. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  1849. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  1850. self.ui.toolbarview.setObjectName('View_TB')
  1851. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  1852. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  1853. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  1854. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  1855. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  1856. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  1857. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  1858. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  1859. else:
  1860. # ## TOOLBAR INSTALLATION # ##
  1861. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  1862. self.ui.toolbarfile.setObjectName('File_TB')
  1863. self.ui.addToolBar(self.ui.toolbarfile)
  1864. self.ui.toolbaredit = QtWidgets.QToolBar('Edit Toolbar')
  1865. self.ui.toolbaredit.setObjectName('Edit_TB')
  1866. self.ui.addToolBar(self.ui.toolbaredit)
  1867. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  1868. self.ui.toolbarview.setObjectName('View_TB')
  1869. self.ui.addToolBar(self.ui.toolbarview)
  1870. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  1871. self.ui.toolbarshell.setObjectName('Shell_TB')
  1872. self.ui.addToolBar(self.ui.toolbarshell)
  1873. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  1874. self.ui.toolbartools.setObjectName('Tools_TB')
  1875. self.ui.addToolBar(self.ui.toolbartools)
  1876. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  1877. # self.ui.exc_edit_toolbar.setVisible(False)
  1878. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  1879. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  1880. self.ui.addToolBarBreak()
  1881. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  1882. # self.ui.geo_edit_toolbar.setVisible(False)
  1883. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  1884. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  1885. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  1886. # self.ui.grb_edit_toolbar.setVisible(False)
  1887. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  1888. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  1889. if current_layout == 'minimal':
  1890. self.ui.toolbarview.setVisible(False)
  1891. self.ui.toolbarshell.setVisible(False)
  1892. self.ui.geo_edit_toolbar.setVisible(False)
  1893. self.ui.grb_edit_toolbar.setVisible(False)
  1894. self.ui.exc_edit_toolbar.setVisible(False)
  1895. self.ui.lock_toolbar(lock=True)
  1896. # add all the actions to the toolbars
  1897. self.ui.populate_toolbars()
  1898. try:
  1899. # reconnect all the signals to the toolbar actions
  1900. self.connect_toolbar_signals()
  1901. except Exception as e:
  1902. self.log.debug(
  1903. "App.on_layout() - connect toolbar signals -> %s" % str(e))
  1904. # Editor Toolbars Signals
  1905. try:
  1906. self.connect_editors_toolbar_signals()
  1907. except Exception as err:
  1908. self.log.debug("App.on_layout() - connect editor signals -> %s" % str(err))
  1909. self.ui.grid_snap_btn.setChecked(True)
  1910. self.ui.corner_snap_btn.setVisible(False)
  1911. self.ui.snap_magnet.setVisible(False)
  1912. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  1913. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  1914. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  1915. self.ui.grid_gap_link_cb.setChecked(True)
  1916. def object2editor(self):
  1917. """
  1918. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1919. :return: None
  1920. """
  1921. self.defaults.report_usage("object2editor()")
  1922. # disable the objects menu as it may interfere with the appEditors
  1923. self.ui.menuobjects.setDisabled(True)
  1924. edited_object = self.collection.get_active()
  1925. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1926. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1927. pass
  1928. else:
  1929. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1930. return
  1931. if isinstance(edited_object, GeometryObject):
  1932. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1933. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1934. # we set the notebook to hidden
  1935. # self.ui.splitter.setSizes([0, 1])
  1936. if edited_object.multigeo is True:
  1937. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1938. if len(sel_rows) > 1:
  1939. self.inform.emit('[WARNING_NOTCL] %s' %
  1940. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1941. "is not possible.\n"
  1942. "Edit only one geometry at a time."))
  1943. if not sel_rows:
  1944. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1945. return
  1946. # determine the tool dia of the selected tool
  1947. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1948. # now find the key in the edited_object.tools that has this tooldia
  1949. multi_tool = 1
  1950. for tool in edited_object.tools:
  1951. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1952. multi_tool = tool
  1953. break
  1954. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1955. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1956. else:
  1957. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1958. self.geo_editor.edit_fcgeometry(edited_object)
  1959. # set call source to the Editor we go into
  1960. self.call_source = 'geo_editor'
  1961. elif isinstance(edited_object, ExcellonObject):
  1962. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1963. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1964. if self.ui.splitter.sizes()[0] == 0:
  1965. self.ui.splitter.setSizes([1, 1])
  1966. self.exc_editor.edit_fcexcellon(edited_object)
  1967. # set call source to the Editor we go into
  1968. self.call_source = 'exc_editor'
  1969. elif isinstance(edited_object, GerberObject):
  1970. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1971. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1972. if self.ui.splitter.sizes()[0] == 0:
  1973. self.ui.splitter.setSizes([1, 1])
  1974. self.grb_editor.edit_fcgerber(edited_object)
  1975. # set call source to the Editor we go into
  1976. self.call_source = 'grb_editor'
  1977. # reset the following variables so the UI is built again after edit
  1978. edited_object.ui_build = False
  1979. elif isinstance(edited_object, CNCJobObject):
  1980. if self.ui.splitter.sizes()[0] == 0:
  1981. self.ui.splitter.setSizes([1, 1])
  1982. # set call source to the Editor we go into
  1983. self.call_source = 'gcode_editor'
  1984. self.gcode_editor.edit_fcgcode(edited_object)
  1985. # make sure that we can't select another object while in Editor Mode:
  1986. self.ui.project_frame.setDisabled(True)
  1987. for idx in range(self.ui.notebook.count()):
  1988. # store the Properties Tab text color here and change the color and text
  1989. if self.ui.notebook.tabText(idx) == _("Properties"):
  1990. self.old_tab_text_color = self.ui.notebook.tabBar.tabTextColor(idx)
  1991. self.ui.notebook.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  1992. self.ui.notebook.tabBar.setTabText(idx, _("Editor"))
  1993. # disable the Project Tab
  1994. if self.ui.notebook.tabText(idx) == _("Project"):
  1995. self.ui.notebook.tabBar.setTabEnabled(idx, False)
  1996. # delete any selection shape that might be active as they are not relevant in Editor
  1997. self.delete_selection_shape()
  1998. # hide the Tools Toolbar
  1999. tools_tb = self.ui.toolbartools
  2000. if tools_tb.isVisible():
  2001. self.old_state_of_tools_toolbar = True
  2002. tools_tb.hide()
  2003. else:
  2004. self.old_state_of_tools_toolbar = False
  2005. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  2006. self.ui.plot_tab_area.protectTab(0)
  2007. self.log.debug("######################### Starting the EDITOR ################################")
  2008. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2009. self.should_we_save = True
  2010. def editor2object(self, cleanup=None):
  2011. """
  2012. Transfers the Geometry or Excellon from it's editor to the current object.
  2013. :return: None
  2014. """
  2015. self.defaults.report_usage("editor2object()")
  2016. # re-enable the objects menu that was disabled on entry in Editor mode
  2017. self.ui.menuobjects.setDisabled(False)
  2018. # do not update a geometry or excellon object unless it comes out of an editor
  2019. if self.call_source != 'app':
  2020. edited_obj = self.collection.get_active()
  2021. if cleanup is None:
  2022. msgbox = QtWidgets.QMessageBox()
  2023. msgbox.setText(_("Do you want to save the edited object?"))
  2024. msgbox.setWindowTitle(_("Exit Editor"))
  2025. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2026. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2027. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2028. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2029. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2030. msgbox.setDefaultButton(bt_yes)
  2031. msgbox.exec_()
  2032. response = msgbox.clickedButton()
  2033. if response == bt_yes:
  2034. # show the Tools Toolbar
  2035. tools_tb = self.ui.toolbartools
  2036. if self.old_state_of_tools_toolbar is True:
  2037. tools_tb.show()
  2038. # clean the Tools Tab
  2039. self.ui.tool_scroll_area.takeWidget()
  2040. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2041. self.ui.notebook.setTabText(2, _("Tool"))
  2042. if edited_obj.kind == 'geometry':
  2043. obj_type = "Geometry"
  2044. self.geo_editor.update_fcgeometry(edited_obj)
  2045. # self.geo_editor.update_options(edited_obj)
  2046. # restore GUI to the Selected TAB
  2047. # Remove anything else in the appGUI
  2048. self.ui.tool_scroll_area.takeWidget()
  2049. # update the geo object options so it is including the bounding box values
  2050. try:
  2051. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  2052. edited_obj.options['xmin'] = xmin
  2053. edited_obj.options['ymin'] = ymin
  2054. edited_obj.options['xmax'] = xmax
  2055. edited_obj.options['ymax'] = ymax
  2056. except AttributeError as e:
  2057. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2058. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2059. edited_obj.build_ui()
  2060. edited_obj.plot()
  2061. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2062. elif edited_obj.kind == 'gerber':
  2063. obj_type = "Gerber"
  2064. self.grb_editor.update_fcgerber()
  2065. # self.grb_editor.update_options(edited_obj)
  2066. # delete the old object (the source object) if it was an empty one
  2067. try:
  2068. if len(edited_obj.solid_geometry) == 0:
  2069. old_name = edited_obj.options['name']
  2070. self.collection.delete_by_name(old_name)
  2071. except TypeError:
  2072. # if the solid_geometry is a single Polygon the len() will not work
  2073. # in any case, falling here means that we have something in the solid_geometry, even if only
  2074. # a single Polygon, therefore we pass this
  2075. pass
  2076. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2077. # restore GUI to the Selected TAB
  2078. # Remove anything else in the GUI
  2079. self.ui.properties_scroll_area.takeWidget()
  2080. elif edited_obj.kind == 'excellon':
  2081. obj_type = "Excellon"
  2082. self.exc_editor.update_fcexcellon(edited_obj)
  2083. # self.exc_editor.update_options(edited_obj)
  2084. # restore GUI to the Selected TAB
  2085. # Remove anything else in the GUI
  2086. self.ui.tool_scroll_area.takeWidget()
  2087. # delete the old object (the source object) if it was an empty one
  2088. # find if we have drills:
  2089. has_drills = None
  2090. for tt in edited_obj.tools:
  2091. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  2092. has_drills = True
  2093. break
  2094. # find if we have slots:
  2095. has_slots = None
  2096. for tt in edited_obj.tools:
  2097. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  2098. has_slots = True
  2099. break
  2100. if has_drills is None and has_slots is None:
  2101. old_name = edited_obj.options['name']
  2102. self.collection.delete_by_name(name=old_name)
  2103. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2104. elif edited_obj.kind == 'cncjob':
  2105. obj_type = "CNCJob"
  2106. self.gcode_editor.update_fcgcode(edited_obj)
  2107. # self.exc_editor.update_options(edited_obj)
  2108. # restore GUI to the Selected TAB
  2109. # Remove anything else in the GUI
  2110. self.ui.tool_scroll_area.takeWidget()
  2111. edited_obj.build_ui()
  2112. # close the open tab
  2113. for idx in range(self.ui.plot_tab_area.count()):
  2114. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2115. self.ui.plot_tab_area.closeTab(idx)
  2116. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2117. else:
  2118. self.inform.emit('[WARNING_NOTCL] %s' %
  2119. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2120. return
  2121. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2122. elif response == bt_no:
  2123. # show the Tools Toolbar
  2124. tools_tb = self.ui.toolbartools
  2125. if self.old_state_of_tools_toolbar is True:
  2126. tools_tb.show()
  2127. # clean the Tools Tab
  2128. self.ui.tool_scroll_area.takeWidget()
  2129. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2130. self.ui.notebook.setTabText(2, _("Tool"))
  2131. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2132. if edited_obj.kind == 'geometry':
  2133. self.geo_editor.deactivate()
  2134. edited_obj.build_ui()
  2135. edited_obj.plot()
  2136. elif edited_obj.kind == 'gerber':
  2137. self.grb_editor.deactivate_grb_editor()
  2138. edited_obj.build_ui()
  2139. elif edited_obj.kind == 'excellon':
  2140. self.exc_editor.deactivate()
  2141. edited_obj.build_ui()
  2142. elif edited_obj.kind == 'cncjob':
  2143. self.gcode_editor.deactivate()
  2144. edited_obj.build_ui()
  2145. # close the open tab
  2146. for idx in range(self.ui.plot_tab_area.count()):
  2147. try:
  2148. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2149. self.ui.plot_tab_area.closeTab(idx)
  2150. except AttributeError:
  2151. continue
  2152. else:
  2153. self.inform.emit('[WARNING_NOTCL] %s' %
  2154. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2155. return
  2156. elif response == bt_cancel:
  2157. return
  2158. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2159. # edited_obj.build_ui()
  2160. # Switch notebook to Properties page
  2161. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2162. else:
  2163. # show the Tools Toolbar
  2164. tools_tb = self.ui.toolbartools
  2165. if self.old_state_of_tools_toolbar is True:
  2166. tools_tb.show()
  2167. if isinstance(edited_obj, GeometryObject):
  2168. self.geo_editor.deactivate()
  2169. elif isinstance(edited_obj, GerberObject):
  2170. self.grb_editor.deactivate_grb_editor()
  2171. elif isinstance(edited_obj, ExcellonObject):
  2172. self.exc_editor.deactivate()
  2173. else:
  2174. self.inform.emit('[WARNING_NOTCL] %s' %
  2175. _("Select a Gerber, Geometry or Excellon Object to update."))
  2176. return
  2177. # if notebook is hidden we show it
  2178. if self.ui.splitter.sizes()[0] == 0:
  2179. self.ui.splitter.setSizes([1, 1])
  2180. for idx in range(self.ui.notebook.count()):
  2181. # restore the Properties Tab text and color
  2182. if self.ui.notebook.tabText(idx) == _("Editor"):
  2183. self.ui.notebook.tabBar.setTabTextColor(idx, self.old_tab_text_color)
  2184. self.ui.notebook.tabBar.setTabText(idx, _("Properties"))
  2185. # enable the Project Tab
  2186. if self.ui.notebook.tabText(idx) == _("Project"):
  2187. self.ui.notebook.tabBar.setTabEnabled(idx, True)
  2188. # restore the call_source to app
  2189. self.call_source = 'app'
  2190. self.log.debug("######################### Closing the EDITOR ################################")
  2191. # edited_obj.plot()
  2192. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2193. self.ui.plot_tab_area.protectTab(0)
  2194. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2195. self.ui.project_frame.setDisabled(False)
  2196. def get_last_folder(self):
  2197. """
  2198. Get the folder path from where the last file was opened.
  2199. :return: String, last opened folder path
  2200. """
  2201. return self.defaults["global_last_folder"]
  2202. def get_last_save_folder(self):
  2203. """
  2204. Get the folder path from where the last file was saved.
  2205. :return: String, last saved folder path
  2206. """
  2207. loc = self.defaults["global_last_save_folder"]
  2208. if loc is None:
  2209. loc = self.defaults["global_last_folder"]
  2210. if loc is None:
  2211. loc = os.path.dirname(__file__)
  2212. return loc
  2213. @QtCore.pyqtSlot(str)
  2214. @QtCore.pyqtSlot(str, bool)
  2215. def info(self, msg, shell_echo=True):
  2216. """
  2217. Informs the user. Normally on the status bar, optionally
  2218. also on the shell.
  2219. :param msg: Text to write.
  2220. :type msg: str
  2221. :param shell_echo: Control if to display the message msg in the Shell
  2222. :type shell_echo: bool
  2223. :return: None
  2224. """
  2225. # Type of message in brackets at the beginning of the message.
  2226. match = re.search(r"\[(.*)\](.*)", msg)
  2227. if match:
  2228. level = match.group(1)
  2229. msg_ = match.group(2)
  2230. self.ui.fcinfo.set_status(str(msg_), level=level)
  2231. if shell_echo is True:
  2232. if level.lower() == "error":
  2233. self.shell_message(msg, error=True, show=True)
  2234. elif level.lower() == "warning":
  2235. self.shell_message(msg, warning=True, show=True)
  2236. elif level.lower() == "error_notcl":
  2237. self.shell_message(msg, error=True, show=False)
  2238. elif level.lower() == "warning_notcl":
  2239. self.shell_message(msg, warning=True, show=False)
  2240. elif level.lower() == "success":
  2241. self.shell_message(msg, success=True, show=False)
  2242. elif level.lower() == "selected":
  2243. self.shell_message(msg, selected=True, show=False)
  2244. else:
  2245. self.shell_message(msg, show=False)
  2246. else:
  2247. self.ui.fcinfo.set_status(str(msg), level="info")
  2248. # make sure that if the message is to clear the infobar with a space
  2249. # is not printed over and over on the shell
  2250. if msg != '' and shell_echo is True:
  2251. self.shell_message(msg)
  2252. def info_shell(self, msg, new_line=True):
  2253. self.shell_message(msg=msg, new_line=new_line)
  2254. def save_to_file(self, content_to_save, txt_content):
  2255. """
  2256. Save something to a file.
  2257. :return: None
  2258. """
  2259. self.defaults.report_usage("save_to_file")
  2260. self.log.debug("save_to_file()")
  2261. self.date = str(datetime.today()).rpartition('.')[0]
  2262. self.date = ''.join(c for c in self.date if c not in ':-')
  2263. self.date = self.date.replace(' ', '_')
  2264. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2265. path_to_save = self.defaults["global_last_save_folder"] if \
  2266. self.defaults["global_last_save_folder"] is not None else self.data_path
  2267. try:
  2268. filename, _f = FCFileSaveDialog.get_saved_filename(
  2269. caption=_("Save to file"),
  2270. directory=path_to_save + '/file_' + self.date,
  2271. ext_filter=filter__
  2272. )
  2273. except TypeError:
  2274. filename, _f = FCFileSaveDialog.get_saved_filename(
  2275. caption=_("Save to file"),
  2276. ext_filter=filter__)
  2277. filename = str(filename)
  2278. if filename == "":
  2279. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2280. return
  2281. else:
  2282. try:
  2283. with open(filename, 'w') as f:
  2284. ___ = f.read()
  2285. except PermissionError:
  2286. self.inform.emit('[WARNING] %s' %
  2287. _("Permission denied, saving not possible.\n"
  2288. "Most likely another app is holding the file open and not accessible."))
  2289. return
  2290. except IOError:
  2291. self.log.debug('Creating a new file ...')
  2292. f = open(filename, 'w')
  2293. f.close()
  2294. except Exception:
  2295. e = sys.exc_info()[0]
  2296. App.log.error("Could not load the file.")
  2297. App.log.error(str(e))
  2298. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2299. return
  2300. # Save content
  2301. if filename.rpartition('.')[2].lower() == 'html':
  2302. file_content = content_to_save
  2303. else:
  2304. file_content = txt_content
  2305. try:
  2306. with open(filename, "w") as f:
  2307. f.write(file_content)
  2308. except Exception:
  2309. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2310. return
  2311. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2312. def register_recent(self, kind, filename):
  2313. """
  2314. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2315. dictionary.
  2316. :param kind: type of file that was opened
  2317. :param filename: the path and file name for the file that was opened
  2318. :return:
  2319. """
  2320. self.log.debug("register_recent()")
  2321. self.log.debug(" %s" % kind)
  2322. self.log.debug(" %s" % filename)
  2323. record = {'kind': str(kind), 'filename': str(filename)}
  2324. if record in self.recent:
  2325. return
  2326. if record in self.recent_projects:
  2327. return
  2328. if record['kind'] == 'project':
  2329. self.recent_projects.insert(0, record)
  2330. else:
  2331. self.recent.insert(0, record)
  2332. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2333. self.recent.pop()
  2334. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2335. self.recent_projects.pop()
  2336. try:
  2337. f = open(self.data_path + '/recent.json', 'w')
  2338. except IOError:
  2339. App.log.error("Failed to open recent items file for writing.")
  2340. self.inform.emit('[ERROR_NOTCL] %s' %
  2341. _('Failed to open recent files file for writing.'))
  2342. return
  2343. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2344. f.close()
  2345. try:
  2346. fp = open(self.data_path + '/recent_projects.json', 'w')
  2347. except IOError:
  2348. App.log.error("Failed to open recent items file for writing.")
  2349. self.inform.emit('[ERROR_NOTCL] %s' %
  2350. _('Failed to open recent projects file for writing.'))
  2351. return
  2352. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2353. fp.close()
  2354. # Re-build the recent items menu
  2355. self.setup_recent_items()
  2356. def on_about(self):
  2357. """
  2358. Displays the "about" dialog found in the Menu --> Help.
  2359. :return: None
  2360. """
  2361. self.defaults.report_usage("on_about")
  2362. version = self.version
  2363. version_date = self.version_date
  2364. beta = self.beta
  2365. class AboutDialog(QtWidgets.QDialog):
  2366. def __init__(self, app, parent=None):
  2367. QtWidgets.QDialog.__init__(self, parent)
  2368. self.app = app
  2369. # Icon and title
  2370. self.setWindowIcon(parent.app_icon)
  2371. self.setWindowTitle(_("About"))
  2372. self.resize(600, 200)
  2373. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2374. # self.setStyleSheet(
  2375. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2376. # "background-attachment: fixed"
  2377. # )
  2378. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2379. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2380. # palette = QtGui.QPalette()
  2381. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2382. # self.setPalette(palette)
  2383. logo = QtWidgets.QLabel()
  2384. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2385. title = QtWidgets.QLabel(
  2386. "<font size=8><B>FlatCAM</B></font><BR>"
  2387. "{title}<BR>"
  2388. "<BR>"
  2389. "<BR>"
  2390. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2391. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2392. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2393. "<B>{issue}</B></a><BR>".format(
  2394. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2395. devel=_("Development"),
  2396. down=_("DOWNLOAD"),
  2397. issue=_("Issue tracker"))
  2398. )
  2399. title.setOpenExternalLinks(True)
  2400. closebtn = QtWidgets.QPushButton(_("Close"))
  2401. tab_widget = QtWidgets.QTabWidget()
  2402. description_label = QtWidgets.QLabel(
  2403. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2404. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2405. version=version,
  2406. beta=('BETA' if beta else ''),
  2407. date=version_date,
  2408. arch=platform.architecture()[0])
  2409. )
  2410. description_label.setOpenExternalLinks(True)
  2411. lic_lbl_header = QtWidgets.QLabel(
  2412. '%s:<br>%s<br>' % (
  2413. _('Licensed under the MIT license'),
  2414. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2415. "http://www.opensource.org/licenses/mit-license.php</a>"
  2416. )
  2417. )
  2418. lic_lbl_header.setOpenExternalLinks(True)
  2419. lic_lbl_body = QtWidgets.QLabel(
  2420. _(
  2421. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2422. 'of this software and associated documentation files (the "Software"), to deal\n'
  2423. 'in the Software without restriction, including without limitation the rights\n'
  2424. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2425. 'copies of the Software, and to permit persons to whom the Software is\n'
  2426. 'furnished to do so, subject to the following conditions:\n\n'
  2427. 'The above copyright notice and this permission notice shall be included in\n'
  2428. 'all copies or substantial portions of the Software.\n\n'
  2429. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2430. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2431. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2432. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2433. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2434. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2435. 'THE SOFTWARE.'
  2436. )
  2437. )
  2438. attributions_label = QtWidgets.QLabel(
  2439. _(
  2440. 'Some of the icons used are from the following sources:<br>'
  2441. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2442. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2443. 'title="Flaticon">www.flaticon.com</a></div>'
  2444. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2445. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2446. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2447. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2448. 'title="Flaticon">www.flaticon.com</a></div>'
  2449. )
  2450. )
  2451. attributions_label.setOpenExternalLinks(True)
  2452. # layouts
  2453. layout1 = QtWidgets.QVBoxLayout()
  2454. layout1_1 = QtWidgets.QHBoxLayout()
  2455. layout1_2 = QtWidgets.QHBoxLayout()
  2456. layout2 = QtWidgets.QHBoxLayout()
  2457. layout3 = QtWidgets.QHBoxLayout()
  2458. self.setLayout(layout1)
  2459. layout1.addLayout(layout1_1)
  2460. layout1.addLayout(layout1_2)
  2461. layout1.addLayout(layout2)
  2462. layout1.addLayout(layout3)
  2463. layout1_1.addStretch()
  2464. layout1_1.addWidget(description_label)
  2465. layout1_2.addWidget(tab_widget)
  2466. self.splash_tab = QtWidgets.QWidget()
  2467. self.splash_tab.setObjectName("splash_about")
  2468. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2469. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2470. tab_widget.addTab(self.splash_tab, _("Splash"))
  2471. self.programmmers_tab = QtWidgets.QWidget()
  2472. self.programmmers_tab.setObjectName("programmers_about")
  2473. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2474. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2475. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2476. self.translators_tab = QtWidgets.QWidget()
  2477. self.translators_tab.setObjectName("translators_about")
  2478. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2479. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2480. tab_widget.addTab(self.translators_tab, _("Translators"))
  2481. self.license_tab = QtWidgets.QWidget()
  2482. self.license_tab.setObjectName("license_about")
  2483. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2484. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2485. tab_widget.addTab(self.license_tab, _("License"))
  2486. self.attributions_tab = QtWidgets.QWidget()
  2487. self.attributions_tab.setObjectName("attributions_about")
  2488. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2489. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2490. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2491. self.splash_tab_layout.addWidget(logo, stretch=0)
  2492. self.splash_tab_layout.addWidget(title, stretch=1)
  2493. pal = QtGui.QPalette()
  2494. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2495. self.prog_grid_lay = QtWidgets.QGridLayout()
  2496. self.prog_grid_lay.setHorizontalSpacing(20)
  2497. self.prog_grid_lay.setColumnStretch(0, 0)
  2498. self.prog_grid_lay.setColumnStretch(2, 1)
  2499. prog_widget = QtWidgets.QWidget()
  2500. prog_widget.setLayout(self.prog_grid_lay)
  2501. prog_scroll = QtWidgets.QScrollArea()
  2502. prog_scroll.setWidget(prog_widget)
  2503. prog_scroll.setWidgetResizable(True)
  2504. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2505. prog_scroll.setPalette(pal)
  2506. self.programmmers_tab_layout.addWidget(prog_scroll)
  2507. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2508. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2509. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2510. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2511. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2512. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2513. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2514. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2515. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2516. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2517. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2518. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2519. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2520. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2521. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2522. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2523. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2524. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2525. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2526. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2527. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2528. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2529. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2530. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2531. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2532. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2533. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2534. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2535. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2536. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2537. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2538. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2539. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2540. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2541. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2542. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2543. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2544. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2545. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2546. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2547. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2548. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2549. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2550. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2551. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2552. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2553. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2554. self.translator_grid_lay = QtWidgets.QGridLayout()
  2555. self.translator_grid_lay.setColumnStretch(0, 0)
  2556. self.translator_grid_lay.setColumnStretch(1, 0)
  2557. self.translator_grid_lay.setColumnStretch(2, 1)
  2558. self.translator_grid_lay.setColumnStretch(3, 0)
  2559. # trans_widget = QtWidgets.QWidget()
  2560. # trans_widget.setLayout(self.translator_grid_lay)
  2561. # self.translators_tab_layout.addWidget(trans_widget)
  2562. # self.translators_tab_layout.addStretch()
  2563. trans_widget = QtWidgets.QWidget()
  2564. trans_widget.setLayout(self.translator_grid_lay)
  2565. trans_scroll = QtWidgets.QScrollArea()
  2566. trans_scroll.setWidget(trans_widget)
  2567. trans_scroll.setWidgetResizable(True)
  2568. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2569. trans_scroll.setPalette(pal)
  2570. self.translators_tab_layout.addWidget(trans_scroll)
  2571. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2572. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2573. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2574. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2575. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2576. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2577. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2578. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2579. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2580. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Olivier Cornet"), 2, 2)
  2581. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2582. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2583. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2584. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2585. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2586. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2587. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2588. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2589. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2590. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2591. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2592. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2593. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2594. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2595. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2596. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2597. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2598. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2599. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2600. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2601. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2602. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2603. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2604. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2605. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2606. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2607. self.translator_grid_lay.setColumnStretch(0, 0)
  2608. self.translators_tab_layout.addStretch()
  2609. self.license_tab_layout.addWidget(lic_lbl_header)
  2610. self.license_tab_layout.addWidget(lic_lbl_body)
  2611. self.license_tab_layout.addStretch()
  2612. self.attributions_tab_layout.addWidget(attributions_label)
  2613. self.attributions_tab_layout.addStretch()
  2614. layout3.addStretch()
  2615. layout3.addWidget(closebtn)
  2616. closebtn.clicked.connect(self.accept)
  2617. AboutDialog(app=self, parent=self.ui).exec_()
  2618. def on_howto(self):
  2619. """
  2620. Displays the "about" dialog found in the Menu --> Help.
  2621. :return: None
  2622. """
  2623. class HowtoDialog(QtWidgets.QDialog):
  2624. def __init__(self, app, parent=None):
  2625. QtWidgets.QDialog.__init__(self, parent)
  2626. self.app = app
  2627. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2628. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2629. "<b>click</b></a>"
  2630. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2631. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2632. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2633. # Icon and title
  2634. self.setWindowIcon(parent.app_icon)
  2635. self.setWindowTitle('%s ...' % _("How To"))
  2636. self.resize(750, 375)
  2637. logo = QtWidgets.QLabel()
  2638. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2639. # content = QtWidgets.QLabel(
  2640. # "%s<br>"
  2641. # "%s<br><br>"
  2642. # "%s,<br>"
  2643. # "%s<br>"
  2644. # "<ul>"
  2645. # "<li> &nbsp;%s %s</li>"
  2646. # "<li> &nbsp;%s %s</li>"
  2647. # "</ul>"
  2648. # "%s %s.<br>"
  2649. # "%s"
  2650. # "<ul>"
  2651. # "<li> &nbsp;%s &#128077;</li>"
  2652. # "<li> &nbsp;%s &#128513;</li>"
  2653. # "</ul>" %
  2654. # (
  2655. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2656. # _("Yet it cannot evolve without <b>contributions</b>."),
  2657. # _("If you want to see this application grow and become better and better"),
  2658. # _("you can <b>contribute</b> to the development yourself by:"),
  2659. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2660. # new_features_link,
  2661. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2662. # bugs_link,
  2663. # _("If you like or use this program you can make a donation"),
  2664. # donation_link,
  2665. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2666. # _("it will be welcomed with joy"),
  2667. # _("it will give me a reason to continue")
  2668. # )
  2669. # )
  2670. # font-weight: bold;
  2671. content = QtWidgets.QLabel(
  2672. "%s<br>"
  2673. "%s<br><br>"
  2674. "%s,<br>"
  2675. "%s<br>"
  2676. "<ul>"
  2677. "<li> &nbsp;%s %s</li>"
  2678. "<li> &nbsp;%s %s</li>"
  2679. "</ul>"
  2680. "<br><br>"
  2681. "%s <br>"
  2682. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2683. (
  2684. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2685. _("Yet it cannot evolve without <b>contributions</b>."),
  2686. _("If you want to see this application grow and become better and better"),
  2687. _("you can <b>contribute</b> to the development yourself by:"),
  2688. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2689. new_features_link,
  2690. _("Bug Reports by providing the steps required to reproduce the bug"),
  2691. bugs_link,
  2692. _("If you like what you have seen so far ..."),
  2693. _("Donations are NOT required."), _("But they are welcomed"),
  2694. donation_link
  2695. )
  2696. )
  2697. content.setOpenExternalLinks(True)
  2698. # palette
  2699. pal = QtGui.QPalette()
  2700. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2701. # layouts
  2702. main_layout = QtWidgets.QVBoxLayout()
  2703. self.setLayout(main_layout)
  2704. tab_layout = QtWidgets.QHBoxLayout()
  2705. buttons_hlay = QtWidgets.QHBoxLayout()
  2706. main_layout.addLayout(tab_layout)
  2707. main_layout.addLayout(buttons_hlay)
  2708. tab_widget = QtWidgets.QTabWidget()
  2709. tab_layout.addWidget(tab_widget)
  2710. closebtn = QtWidgets.QPushButton(_("Close"))
  2711. buttons_hlay.addStretch()
  2712. buttons_hlay.addWidget(closebtn)
  2713. # CONTRIBUTE section
  2714. self.intro_tab = QtWidgets.QWidget()
  2715. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2716. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2717. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2718. self.grid_lay = QtWidgets.QGridLayout()
  2719. self.grid_lay.setHorizontalSpacing(20)
  2720. self.grid_lay.setColumnStretch(0, 0)
  2721. self.grid_lay.setColumnStretch(1, 1)
  2722. intro_wdg = QtWidgets.QWidget()
  2723. intro_wdg.setLayout(self.grid_lay)
  2724. intro_scroll_area = QtWidgets.QScrollArea()
  2725. intro_scroll_area.setWidget(intro_wdg)
  2726. intro_scroll_area.setWidgetResizable(True)
  2727. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2728. intro_scroll_area.setPalette(pal)
  2729. self.grid_lay.addWidget(logo, 0, 0)
  2730. self.grid_lay.addWidget(content, 0, 1)
  2731. self.intro_tab_layout.addWidget(intro_scroll_area)
  2732. # LINKS EXCHANGE section
  2733. self.links_tab = QtWidgets.QWidget()
  2734. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2735. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2736. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2737. self.links_lay = QtWidgets.QHBoxLayout()
  2738. links_wdg = QtWidgets.QWidget()
  2739. links_wdg.setLayout(self.links_lay)
  2740. links_scroll_area = QtWidgets.QScrollArea()
  2741. links_scroll_area.setWidget(links_wdg)
  2742. links_scroll_area.setWidgetResizable(True)
  2743. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2744. links_scroll_area.setPalette(pal)
  2745. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2746. self.links_tab_layout.addWidget(links_scroll_area)
  2747. # HOW TO section
  2748. self.howto_tab = QtWidgets.QWidget()
  2749. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2750. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2751. tab_widget.addTab(self.howto_tab, _("How To's"))
  2752. self.howto_lay = QtWidgets.QHBoxLayout()
  2753. howto_wdg = QtWidgets.QWidget()
  2754. howto_wdg.setLayout(self.howto_lay)
  2755. howto_scroll_area = QtWidgets.QScrollArea()
  2756. howto_scroll_area.setWidget(howto_wdg)
  2757. howto_scroll_area.setWidgetResizable(True)
  2758. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2759. howto_scroll_area.setPalette(pal)
  2760. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2761. self.howto_tab_layout.addWidget(howto_scroll_area)
  2762. # BUTTONS section
  2763. closebtn.clicked.connect(self.accept)
  2764. HowtoDialog(app=self, parent=self.ui).exec_()
  2765. def install_bookmarks(self, book_dict=None):
  2766. """
  2767. Install the bookmarks actions in the Help menu -> Bookmarks
  2768. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2769. :return: None
  2770. """
  2771. if book_dict is None:
  2772. self.defaults["global_bookmarks"].update(
  2773. {
  2774. '1': ['FlatCAM', "http://flatcam.org"],
  2775. '2': [_('Backup Site'), ""]
  2776. }
  2777. )
  2778. else:
  2779. self.defaults["global_bookmarks"].clear()
  2780. self.defaults["global_bookmarks"].update(book_dict)
  2781. # first try to disconnect if somehow they get connected from elsewhere
  2782. for act in self.ui.menuhelp_bookmarks.actions():
  2783. try:
  2784. act.triggered.disconnect()
  2785. except TypeError:
  2786. pass
  2787. # clear all actions except the last one who is the Bookmark manager
  2788. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2789. pass
  2790. else:
  2791. self.ui.menuhelp_bookmarks.removeAction(act)
  2792. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2793. if self.defaults["global_bookmarks"]:
  2794. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2795. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2796. # the JSON is first making the keys as strings (therefore I have to use strings too
  2797. # or do the conversion :(
  2798. # )
  2799. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2800. # the '10' entry jsut after '1' therefore ordering as strings
  2801. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2802. key=lambda x: int(x[0]))
  2803. for entry, bookmark in sorted_bookmarks:
  2804. title = bookmark[0]
  2805. weblink = bookmark[1]
  2806. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2807. act.setText(title)
  2808. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2809. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2810. if title == _('Backup Site') and weblink == "":
  2811. act.triggered.connect(self.on_backup_site)
  2812. else:
  2813. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2814. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2815. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2816. def on_bookmarks_manager(self):
  2817. """
  2818. Adds the bookmark manager in a Tab in Plot Area
  2819. :return:
  2820. """
  2821. for idx in range(self.ui.plot_tab_area.count()):
  2822. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2823. # there can be only one instance of Bookmark Manager at one time
  2824. return
  2825. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2826. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2827. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2828. # add the tab if it was closed
  2829. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2830. # delete the absolute and relative position and messages in the infobar
  2831. # self.ui.position_label.setText("")
  2832. # self.ui.rel_position_label.setText("")
  2833. # hide coordinates toolbars in the infobar while in DB
  2834. self.ui.coords_toolbar.hide()
  2835. self.ui.delta_coords_toolbar.hide()
  2836. # Switch plot_area to preferences page
  2837. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2838. def on_backup_site(self):
  2839. msgbox = QtWidgets.QMessageBox()
  2840. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2841. "1. FlatCAM.org website is down\n"
  2842. "2. Someone forked FlatCAM project and wants to point\n"
  2843. "to his own website\n\n"
  2844. "If you can't get any informations about the application\n"
  2845. "use the YouTube channel link from the Help menu."))
  2846. msgbox.setWindowTitle(_("Alternative website"))
  2847. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2848. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2849. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2850. msgbox.setDefaultButton(bt_yes)
  2851. msgbox.exec_()
  2852. # response = msgbox.clickedButton()
  2853. def final_save(self):
  2854. """
  2855. Callback for doing a preferences save to file whenever the application is about to quit.
  2856. If the project has changes, it will ask the user to save the project.
  2857. :return: None
  2858. """
  2859. if self.save_in_progress:
  2860. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2861. return
  2862. if self.should_we_save and self.collection.get_list():
  2863. msgbox = QtWidgets.QMessageBox()
  2864. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2865. "\n"
  2866. "Do you want to Save the project?"))
  2867. msgbox.setWindowTitle(_("Save changes"))
  2868. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2869. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2870. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2871. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2872. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2873. msgbox.setDefaultButton(bt_yes)
  2874. msgbox.exec_()
  2875. response = msgbox.clickedButton()
  2876. if response == bt_yes:
  2877. try:
  2878. self.trayIcon.hide()
  2879. except Exception:
  2880. pass
  2881. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2882. elif response == bt_no:
  2883. try:
  2884. self.trayIcon.hide()
  2885. except Exception:
  2886. pass
  2887. self.quit_application()
  2888. elif response == bt_cancel:
  2889. return
  2890. else:
  2891. try:
  2892. self.trayIcon.hide()
  2893. except Exception:
  2894. pass
  2895. self.quit_application()
  2896. def quit_application(self):
  2897. """
  2898. Called (as a pyslot or not) when the application is quit.
  2899. :return: None
  2900. """
  2901. # close editors before quiting the app, if they are open
  2902. if self.call_source == 'geo_editor':
  2903. self.geo_editor.deactivate()
  2904. try:
  2905. self.geo_editor.disconnect()
  2906. except TypeError:
  2907. pass
  2908. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2909. if self.call_source == 'exc_editor':
  2910. self.exc_editor.deactivate()
  2911. try:
  2912. self.grb_editor.disconnect()
  2913. except TypeError:
  2914. pass
  2915. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2916. if self.call_source == 'grb_editor':
  2917. self.grb_editor.deactivate_grb_editor()
  2918. try:
  2919. self.exc_editor.disconnect()
  2920. except TypeError:
  2921. pass
  2922. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2923. # disconnect the mouse events
  2924. if self.is_legacy:
  2925. self.plotcanvas.graph_event_disconnect(self.mm)
  2926. self.plotcanvas.graph_event_disconnect(self.mp)
  2927. self.plotcanvas.graph_event_disconnect(self.mr)
  2928. self.plotcanvas.graph_event_disconnect(self.mdc)
  2929. self.plotcanvas.graph_event_disconnect(self.kp)
  2930. else:
  2931. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2932. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2933. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2934. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2935. self.on_mouse_double_click_over_plot)
  2936. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2937. self.preferencesUiManager.save_defaults(silent=True)
  2938. self.log.debug("App.quit_application() --> App Defaults saved.")
  2939. if self.cmd_line_headless != 1:
  2940. # save app state to file
  2941. stgs = QSettings("Open Source", "FlatCAM")
  2942. stgs.setValue('saved_gui_state', self.ui.saveState())
  2943. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2944. stgs.setValue(
  2945. 'language',
  2946. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2947. )
  2948. stgs.setValue(
  2949. 'notebook_font_size',
  2950. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2951. )
  2952. stgs.setValue(
  2953. 'axis_font_size',
  2954. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2955. )
  2956. stgs.setValue(
  2957. 'textbox_font_size',
  2958. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2959. )
  2960. stgs.setValue(
  2961. 'hud_font_size',
  2962. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2963. )
  2964. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2965. stgs.setValue(
  2966. 'machinist',
  2967. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2968. )
  2969. # This will write the setting to the platform specific storage.
  2970. del stgs
  2971. self.log.debug("App.quit_application() --> App UI state saved.")
  2972. # try to quit the Socket opened by ArgsThread class
  2973. try:
  2974. # self.new_launch.thread_exit = True
  2975. # self.new_launch.listener.close()
  2976. self.new_launch.stop.emit()
  2977. except Exception as err:
  2978. self.log.debug("App.quit_application() --> %s" % str(err))
  2979. # try to quit the QThread that run ArgsThread class
  2980. try:
  2981. # del self.new_launch
  2982. self.listen_th.quit()
  2983. except Exception as e:
  2984. self.log.debug("App.quit_application() --> %s" % str(e))
  2985. # terminate workers
  2986. # self.workers.__del__()
  2987. self.clear_pool()
  2988. # quit app by signalling for self.kill_app() method
  2989. # self.close_app_signal.emit()
  2990. QtWidgets.qApp.quit()
  2991. sys.exit(0)
  2992. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2993. # we use the following command
  2994. # minor_v = sys.version_info.minor
  2995. # if minor_v < 8:
  2996. # # make sure that the app closes
  2997. # sys.exit(0)
  2998. # else:
  2999. # os._exit(0) # fix to work with Python 3.8
  3000. @staticmethod
  3001. def kill_app():
  3002. QtWidgets.qApp.quit()
  3003. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3004. # we use the following command
  3005. sys.exit(0)
  3006. def on_portable_checked(self, state):
  3007. """
  3008. Callback called when the checkbox in Preferences GUI is checked.
  3009. It will set the application as portable by creating the preferences and recent files in the
  3010. 'config' folder found in the FlatCAM installation folder.
  3011. :param state: boolean, the state of the checkbox when clicked/checked
  3012. :return:
  3013. """
  3014. line_no = 0
  3015. data = None
  3016. if sys.platform != 'win32':
  3017. # this won't work in Linux or MacOS
  3018. return
  3019. # test if the app was frozen and choose the path for the configuration file
  3020. if getattr(sys, "frozen", False) is True:
  3021. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3022. else:
  3023. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3024. config_file = current_data_path + '\\configuration.txt'
  3025. try:
  3026. with open(config_file, 'r') as f:
  3027. try:
  3028. data = f.readlines()
  3029. except Exception as e:
  3030. self.log.debug('App.__init__() -->%s' % str(e))
  3031. return
  3032. except FileNotFoundError:
  3033. pass
  3034. for line in data:
  3035. line = line.strip('\n')
  3036. param = str(line).rpartition('=')
  3037. if param[0] == 'portable':
  3038. break
  3039. line_no += 1
  3040. if state:
  3041. data[line_no] = 'portable=True\n'
  3042. # create the new defauults files
  3043. # create current_defaults.FlatConfig file if there is none
  3044. try:
  3045. f = open(current_data_path + '/current_defaults.FlatConfig')
  3046. f.close()
  3047. except IOError:
  3048. self.log.debug('Creating empty current_defaults.FlatConfig')
  3049. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3050. json.dump({}, f)
  3051. f.close()
  3052. # create factory_defaults.FlatConfig file if there is none
  3053. try:
  3054. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3055. f.close()
  3056. except IOError:
  3057. self.log.debug('Creating empty factory_defaults.FlatConfig')
  3058. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3059. json.dump({}, f)
  3060. f.close()
  3061. try:
  3062. f = open(current_data_path + '/recent.json')
  3063. f.close()
  3064. except IOError:
  3065. self.log.debug('Creating empty recent.json')
  3066. f = open(current_data_path + '/recent.json', 'w')
  3067. json.dump([], f)
  3068. f.close()
  3069. try:
  3070. fp = open(current_data_path + '/recent_projects.json')
  3071. fp.close()
  3072. except IOError:
  3073. self.log.debug('Creating empty recent_projects.json')
  3074. fp = open(current_data_path + '/recent_projects.json', 'w')
  3075. json.dump([], fp)
  3076. fp.close()
  3077. # save the current defaults to the new defaults file
  3078. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3079. else:
  3080. data[line_no] = 'portable=False\n'
  3081. with open(config_file, 'w') as f:
  3082. f.writelines(data)
  3083. def on_register_files(self, obj_type=None):
  3084. """
  3085. Called whenever there is a need to register file extensions with FlatCAM.
  3086. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3087. :param obj_type: the type of object to be register for.
  3088. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3089. :return: None
  3090. """
  3091. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3092. new_reg_path = 'Software\\Classes\\'
  3093. # find if the current user is admin
  3094. try:
  3095. is_admin = os.getuid() == 0
  3096. except AttributeError:
  3097. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3098. if is_admin is True:
  3099. root_path = winreg.HKEY_LOCAL_MACHINE
  3100. else:
  3101. root_path = winreg.HKEY_CURRENT_USER
  3102. # create the keys
  3103. def set_reg(name, root_pth, new_reg_path_par, value):
  3104. try:
  3105. winreg.CreateKey(root_pth, new_reg_path_par)
  3106. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  3107. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3108. return True
  3109. except WindowsError:
  3110. return False
  3111. # delete key in registry
  3112. def delete_reg(root_pth, reg_path, key_to_del):
  3113. key_to_del_path = reg_path + key_to_del
  3114. try:
  3115. winreg.DeleteKey(root_pth, key_to_del_path)
  3116. return True
  3117. except WindowsError:
  3118. return False
  3119. if obj_type is None or obj_type == 'excellon':
  3120. exc_list = \
  3121. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3122. exc_list = [x for x in exc_list if x != '']
  3123. # register all keys in the Preferences window
  3124. for ext in exc_list:
  3125. new_k = new_reg_path + '.%s' % ext
  3126. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3127. # and unregister those that are no longer in the Preferences windows but are in the file
  3128. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3129. if ext not in exc_list:
  3130. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3131. # now write the updated extensions to the self.defaults
  3132. # new_ext = ''
  3133. # for ext in exc_list:
  3134. # new_ext = new_ext + ext + ', '
  3135. # self.defaults["fa_excellon"] = new_ext
  3136. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3137. if obj_type is None or obj_type == 'gcode':
  3138. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3139. gco_list = [x for x in gco_list if x != '']
  3140. # register all keys in the Preferences window
  3141. for ext in gco_list:
  3142. new_k = new_reg_path + '.%s' % ext
  3143. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3144. # and unregister those that are no longer in the Preferences windows but are in the file
  3145. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3146. if ext not in gco_list:
  3147. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3148. self.inform.emit('[success] %s' %
  3149. _("Selected GCode file extensions registered with FlatCAM."))
  3150. if obj_type is None or obj_type == 'gerber':
  3151. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3152. grb_list = [x for x in grb_list if x != '']
  3153. # register all keys in the Preferences window
  3154. for ext in grb_list:
  3155. new_k = new_reg_path + '.%s' % ext
  3156. set_reg('', root_pth=root_path, new_reg_path_par=new_k, value='FlatCAM')
  3157. # and unregister those that are no longer in the Preferences windows but are in the file
  3158. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3159. if ext not in grb_list:
  3160. delete_reg(root_pth=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3161. self.inform.emit('[success] %s' % _("Selected Gerber file extensions registered with FlatCAM."))
  3162. def add_extension(self, ext_type):
  3163. """
  3164. Add a file extension to the list for a specific object
  3165. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3166. :return:
  3167. """
  3168. if ext_type == 'excellon':
  3169. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3170. if new_ext == '':
  3171. return
  3172. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3173. if new_ext in old_val:
  3174. return
  3175. old_val.append(new_ext)
  3176. old_val.sort()
  3177. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3178. if ext_type == 'gcode':
  3179. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3180. if new_ext == '':
  3181. return
  3182. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3183. if new_ext in old_val:
  3184. return
  3185. old_val.append(new_ext)
  3186. old_val.sort()
  3187. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3188. if ext_type == 'gerber':
  3189. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3190. if new_ext == '':
  3191. return
  3192. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3193. if new_ext in old_val:
  3194. return
  3195. old_val.append(new_ext)
  3196. old_val.sort()
  3197. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3198. if ext_type == 'keyword':
  3199. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3200. if new_kw == '':
  3201. return
  3202. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3203. if new_kw in old_val:
  3204. return
  3205. old_val.append(new_kw)
  3206. old_val.sort()
  3207. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3208. # update the self.myKeywords so the model is updated
  3209. self.autocomplete_kw_list = \
  3210. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3211. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3212. self.shell.command_line().set_model_data(self.myKeywords)
  3213. def del_extension(self, ext_type):
  3214. """
  3215. Remove a file extension from the list for a specific object
  3216. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3217. :return:
  3218. """
  3219. if ext_type == 'excellon':
  3220. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3221. if new_ext == '':
  3222. return
  3223. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3224. if new_ext not in old_val:
  3225. return
  3226. old_val.remove(new_ext)
  3227. old_val.sort()
  3228. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3229. if ext_type == 'gcode':
  3230. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3231. if new_ext == '':
  3232. return
  3233. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3234. if new_ext not in old_val:
  3235. return
  3236. old_val.remove(new_ext)
  3237. old_val.sort()
  3238. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3239. if ext_type == 'gerber':
  3240. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3241. if new_ext == '':
  3242. return
  3243. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3244. if new_ext not in old_val:
  3245. return
  3246. old_val.remove(new_ext)
  3247. old_val.sort()
  3248. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3249. if ext_type == 'keyword':
  3250. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3251. if new_kw == '':
  3252. return
  3253. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3254. if new_kw not in old_val:
  3255. return
  3256. old_val.remove(new_kw)
  3257. old_val.sort()
  3258. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3259. # update the self.myKeywords so the model is updated
  3260. self.autocomplete_kw_list = \
  3261. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3262. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3263. self.shell.command_line().set_model_data(self.myKeywords)
  3264. def restore_extensions(self, ext_type):
  3265. """
  3266. Restore all file extensions associations with FlatCAM, for a specific object
  3267. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3268. :return:
  3269. """
  3270. if ext_type == 'excellon':
  3271. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3272. # for the ability to open Excellon files with .txt extension
  3273. new_exc_list = deepcopy(self.exc_list)
  3274. try:
  3275. new_exc_list.remove('txt')
  3276. except ValueError:
  3277. pass
  3278. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3279. if ext_type == 'gcode':
  3280. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3281. if ext_type == 'gerber':
  3282. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3283. if ext_type == 'keyword':
  3284. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3285. # update the self.myKeywords so the model is updated
  3286. self.autocomplete_kw_list = self.default_keywords
  3287. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3288. self.shell.commnad_line().set_model_data(self.myKeywords)
  3289. def delete_all_extensions(self, ext_type):
  3290. """
  3291. Delete all file extensions associations with FlatCAM, for a specific object
  3292. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3293. :return:
  3294. """
  3295. if ext_type == 'excellon':
  3296. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3297. if ext_type == 'gcode':
  3298. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3299. if ext_type == 'gerber':
  3300. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3301. if ext_type == 'keyword':
  3302. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3303. # update the self.myKeywords so the model is updated
  3304. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3305. self.shell.command_line().set_model_data(self.myKeywords)
  3306. def on_edit_join(self, name=None):
  3307. """
  3308. Callback for Edit->Join. Joins the selected geometry objects into
  3309. a new one.
  3310. :return: None
  3311. """
  3312. self.defaults.report_usage("on_edit_join()")
  3313. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3314. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3315. geo_type_set = set()
  3316. objs = self.collection.get_selected()
  3317. if len(objs) < 2:
  3318. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3319. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3320. return 'fail'
  3321. for obj in objs:
  3322. geo_type_set.add(obj.multigeo)
  3323. # if len(geo_type_list) == 1 means that all list elements are the same
  3324. if len(geo_type_set) != 1:
  3325. self.inform.emit('[ERROR] %s' %
  3326. _("Failed join. The Geometry objects are of different types.\n"
  3327. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3328. "convert from one to another and retry joining \n"
  3329. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3330. "the result may not be what was expected. \n"
  3331. "Check the generated GCODE."))
  3332. return
  3333. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3334. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3335. if True in geo_type_set:
  3336. def initialize(geo_obj, app):
  3337. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multi_geo=True, fuse_tools=fuse_tools)
  3338. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3339. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3340. for v in geo_obj.tools.values():
  3341. v['data']['name'] = obj_name_multi
  3342. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3343. else:
  3344. def initialize(geo_obj, app):
  3345. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multi_geo=False, fuse_tools=fuse_tools)
  3346. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3347. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3348. for v in geo_obj.tools.values():
  3349. v['data']['name'] = obj_name_single
  3350. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3351. self.should_we_save = True
  3352. def on_edit_join_exc(self):
  3353. """
  3354. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3355. a new Excellon.
  3356. :return: None
  3357. """
  3358. self.defaults.report_usage("on_edit_join_exc()")
  3359. objs = self.collection.get_selected()
  3360. for obj in objs:
  3361. if not isinstance(obj, ExcellonObject):
  3362. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3363. return
  3364. if len(objs) < 2:
  3365. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3366. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3367. return 'fail'
  3368. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3369. def initialize(exc_obj, app):
  3370. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3371. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3372. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3373. self.should_we_save = True
  3374. def on_edit_join_grb(self):
  3375. """
  3376. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3377. a new Gerber object.
  3378. :return: None
  3379. """
  3380. self.defaults.report_usage("on_edit_join_grb()")
  3381. objs = self.collection.get_selected()
  3382. for obj in objs:
  3383. if not isinstance(obj, GerberObject):
  3384. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3385. return
  3386. if len(objs) < 2:
  3387. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3388. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3389. return 'fail'
  3390. def initialize(grb_obj, app):
  3391. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3392. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3393. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3394. self.should_we_save = True
  3395. def on_convert_singlegeo_to_multigeo(self):
  3396. """
  3397. Called for converting a Geometry object from single-geo to multi-geo.
  3398. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3399. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3400. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3401. the solid-geometry of that tool.
  3402. :return: None
  3403. """
  3404. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3405. obj = self.collection.get_active()
  3406. if obj is None:
  3407. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3408. return
  3409. if not isinstance(obj, GeometryObject):
  3410. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3411. return
  3412. obj.multigeo = True
  3413. for tooluid, dict_value in obj.tools.items():
  3414. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3415. if not isinstance(obj.solid_geometry, list):
  3416. obj.solid_geometry = [obj.solid_geometry]
  3417. # obj.solid_geometry[:] = []
  3418. obj.plot()
  3419. self.should_we_save = True
  3420. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3421. def on_convert_multigeo_to_singlegeo(self):
  3422. """
  3423. Called for converting a Geometry object from multi-geo to single-geo.
  3424. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3425. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3426. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3427. the solid-geometry of that tool.
  3428. :return: None
  3429. """
  3430. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3431. obj = self.collection.get_active()
  3432. if obj is None:
  3433. self.inform.emit('[ERROR_NOTCL] %s' %
  3434. _("Failed. Select a Geometry Object and try again."))
  3435. return
  3436. if not isinstance(obj, GeometryObject):
  3437. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3438. (_("Expected a GeometryObject, got"), type(obj)))
  3439. return
  3440. obj.multigeo = False
  3441. total_solid_geometry = []
  3442. for tooluid, dict_value in obj.tools.items():
  3443. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3444. # clear the original geometry
  3445. dict_value['solid_geometry'][:] = []
  3446. obj.solid_geometry = deepcopy(total_solid_geometry)
  3447. obj.plot()
  3448. self.should_we_save = True
  3449. self.inform.emit('[success] %s' %
  3450. _("A Geometry object was converted to SingleGeo type."))
  3451. def on_defaults_dict_change(self, field):
  3452. """
  3453. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3454. Edit -> Preferences tab window.
  3455. :param field: the key of the self.defaults dictionary that was changed.
  3456. :return: None
  3457. """
  3458. self.preferencesUiManager.defaults_write_form_field(field=field)
  3459. if field == "units":
  3460. self.set_screen_units(self.defaults['units'])
  3461. def set_screen_units(self, units):
  3462. """
  3463. Set the FlatCAM units on the status bar.
  3464. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3465. :return: None
  3466. """
  3467. self.ui.units_label.setText("[" + units.lower() + "]")
  3468. def on_toggle_units_click(self):
  3469. try:
  3470. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3471. except (TypeError, AttributeError):
  3472. pass
  3473. if self.defaults["units"] == 'MM':
  3474. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3475. else:
  3476. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3477. self.on_toggle_units(no_pref=True)
  3478. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3479. lambda: self.on_toggle_units(no_pref=False))
  3480. def scale_defaults(self, sfactor, dimensions):
  3481. for dim in dimensions:
  3482. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3483. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3484. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3485. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3486. if not self.defaults[dim] or self.defaults[dim] == '':
  3487. continue
  3488. if isinstance(self.defaults[dim], str):
  3489. try:
  3490. tools_diameters = eval(self.defaults[dim])
  3491. except Exception as e:
  3492. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3493. continue
  3494. elif isinstance(self.defaults[dim], (float, int)):
  3495. tools_diameters = [self.defaults[dim]]
  3496. else:
  3497. tools_diameters = list(self.defaults[dim])
  3498. if isinstance(tools_diameters, (tuple, list)):
  3499. pass
  3500. elif isinstance(tools_diameters, (int, float)):
  3501. tools_diameters = [self.defaults[dim]]
  3502. else:
  3503. continue
  3504. td_len = len(tools_diameters)
  3505. conv_list = []
  3506. for t in range(td_len):
  3507. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3508. self.defaults[dim] = conv_list
  3509. elif dim in ['global_gridx', 'global_gridy']:
  3510. # format the number of decimals to the one specified in self.decimals
  3511. try:
  3512. val = float(self.defaults[dim]) * sfactor
  3513. except Exception as e:
  3514. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3515. continue
  3516. self.defaults[dim] = self.dec_format(val, self.decimals)
  3517. else:
  3518. # the number of decimals for the rest is kept unchanged
  3519. if self.defaults[dim]:
  3520. try:
  3521. val = float(self.defaults[dim]) * sfactor
  3522. except Exception as e:
  3523. self.log.debug(
  3524. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3525. )
  3526. continue
  3527. self.defaults[dim] = self.dec_format(val, self.decimals)
  3528. def on_toggle_units(self, no_pref=False):
  3529. """
  3530. Callback for the Units radio-button change in the Preferences tab.
  3531. Changes the application's default units adn for the project too.
  3532. If changing the project's units, the change propagates to all of
  3533. the objects in the project.
  3534. :return: None
  3535. """
  3536. self.defaults.report_usage("on_toggle_units")
  3537. if self.toggle_units_ignore:
  3538. return
  3539. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3540. # If option is the same, then ignore
  3541. if new_units == self.defaults["units"].upper():
  3542. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3543. return
  3544. # Keys in self.defaults for which to scale their values
  3545. dimensions = [
  3546. # Global
  3547. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3548. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3549. # Gerber Object
  3550. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3551. # Gerber Editor
  3552. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3553. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3554. # Excellon Object
  3555. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3556. # Excellon Editor
  3557. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3558. "excellon_editor_slot_length",
  3559. # Geometry Object
  3560. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3561. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3562. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3563. "geometry_extracut_length", "geometry_z_pdepth",
  3564. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3565. # CNCJob Object
  3566. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3567. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3568. # Isolation Tool
  3569. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3570. # Drilling Tool
  3571. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3572. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3573. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3574. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3575. # NCC Tool
  3576. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3577. "tools_ncc_newdia",
  3578. # Cutout Tool
  3579. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3580. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3581. # Paint Tool
  3582. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3583. # 2Sided Tool
  3584. "tools_2sided_drilldia",
  3585. # Film Tool
  3586. "tools_film_boundary", "tools_film_scale_stroke",
  3587. # Panel Tool
  3588. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3589. "tools_panelize_constrainy",
  3590. # Calculators Tool
  3591. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3592. # Transform Tool
  3593. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3594. "tools_transform_buffer_dis",
  3595. # SolderPaste Tool
  3596. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3597. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3598. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3599. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3600. # Corner Markers Tool
  3601. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3602. # Check Rules Tool
  3603. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3604. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3605. # QRCode Tool
  3606. "tools_qrcode_border_size",
  3607. # Copper Thieving Tool
  3608. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3609. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3610. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3611. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3612. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3613. "tools_copper_thieving_mask_clearance",
  3614. # Fiducials Tool
  3615. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3616. # Calibration Tool
  3617. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3618. # Drills Extraction Tool
  3619. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3620. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3621. # Punch Gerber Tool
  3622. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3623. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3624. # Invert Gerber Tool
  3625. "tools_invert_margin",
  3626. ]
  3627. # The scaling factor depending on choice of units.
  3628. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3629. # Changing project units. Warn user.
  3630. msgbox = QtWidgets.QMessageBox()
  3631. msgbox.setWindowTitle(_("Toggle Units"))
  3632. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3633. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3634. msgbox.setText(_("Changing the units of the project\n"
  3635. "will scale all objects.\n\n"
  3636. "Do you want to continue?"))
  3637. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3638. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3639. msgbox.setDefaultButton(bt_ok)
  3640. msgbox.exec_()
  3641. response = msgbox.clickedButton()
  3642. if response == bt_ok:
  3643. if no_pref is False:
  3644. self.preferencesUiManager.defaults_read_form()
  3645. self.scale_defaults(factor, dimensions)
  3646. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3647. self.defaults["units"] = new_units
  3648. # update the defaults from form, some may assume that the conversion is enough and it's not
  3649. self.on_options_app2project()
  3650. # update the objects
  3651. for obj in self.collection.get_list():
  3652. obj.convert_units(new_units)
  3653. # make that the properties stored in the object are also updated
  3654. self.app_obj.object_changed.emit(obj)
  3655. # rebuild the object UI
  3656. obj.build_ui()
  3657. # change this only if the workspace is active
  3658. if self.defaults['global_workspace'] is True:
  3659. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3660. # adjust the grid values on the main toolbar
  3661. val_x = float(self.defaults['global_gridx']) * factor
  3662. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3663. current = self.collection.get_active()
  3664. if current is not None:
  3665. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3666. if not isinstance(current, GeometryObject):
  3667. current.to_form()
  3668. # replot all objects
  3669. self.plot_all()
  3670. # set the status labels to reflect the current FlatCAM units
  3671. self.set_screen_units(new_units)
  3672. # signal to the app that we changed the object properties and it should save the project
  3673. self.should_we_save = True
  3674. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3675. else:
  3676. # Undo toggling
  3677. self.toggle_units_ignore = True
  3678. if self.defaults['units'].upper() == 'MM':
  3679. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3680. else:
  3681. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3682. self.toggle_units_ignore = False
  3683. # store the grid values so they are not changed in the next step
  3684. val_x = float(self.defaults['global_gridx'])
  3685. val_y = float(self.defaults['global_gridy'])
  3686. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3687. self.preferencesUiManager.defaults_read_form()
  3688. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3689. # in self.defaults from the GUI elements but
  3690. # I don't want it for the grid values, so I update them here
  3691. self.defaults['global_gridx'] = val_x
  3692. self.defaults['global_gridy'] = val_y
  3693. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3694. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3695. def on_deselect_all(self):
  3696. self.collection.set_all_inactive()
  3697. self.delete_selection_shape()
  3698. def on_workspace_modified(self):
  3699. # self.save_defaults(silent=True)
  3700. self.plotcanvas.delete_workspace()
  3701. self.preferencesUiManager.defaults_read_form()
  3702. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3703. def on_workspace(self):
  3704. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3705. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3706. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3707. else:
  3708. self.plotcanvas.delete_workspace()
  3709. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3710. self.preferencesUiManager.defaults_read_form()
  3711. # self.save_defaults(silent=True)
  3712. def on_workspace_toggle(self):
  3713. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3714. try:
  3715. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3716. except TypeError:
  3717. pass
  3718. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3719. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3720. self.on_workspace()
  3721. def on_cursor_type(self, val):
  3722. """
  3723. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3724. :return: None
  3725. """
  3726. self.app_cursor.enabled = False
  3727. if val == 'small':
  3728. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3729. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3730. self.app_cursor = self.plotcanvas.new_cursor()
  3731. else:
  3732. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3733. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3734. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3735. if self.ui.grid_snap_btn.isChecked():
  3736. self.app_cursor.enabled = True
  3737. else:
  3738. self.app_cursor.enabled = False
  3739. def on_tool_add_keypress(self):
  3740. # ## Current application units in Upper Case
  3741. self.units = self.defaults['units'].upper()
  3742. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3743. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3744. if notebook_widget_name == 'properties_tab':
  3745. if self.collection.get_active().kind == 'geometry':
  3746. # Tool add works for Geometry only if Advanced is True in Preferences
  3747. if self.defaults["global_app_level"] == 'a':
  3748. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3749. text='%s:' % _('Enter a Tool Diameter'),
  3750. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3751. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3752. tool_add_popup.wdg.selectAll()
  3753. val, ok = tool_add_popup.get_value()
  3754. if ok:
  3755. if float(val) == 0:
  3756. self.inform.emit('[WARNING_NOTCL] %s' %
  3757. _("Please enter a tool diameter with non-zero value, in Float format."))
  3758. return
  3759. self.collection.get_active().on_tool_add(clicked_state=False, dia=float(val))
  3760. else:
  3761. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3762. else:
  3763. msgbox = QtWidgets.QMessageBox()
  3764. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3765. "Go to Preferences -> General - Show Advanced Options."))
  3766. msgbox.setWindowTitle("Tool adding ...")
  3767. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3768. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3769. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3770. msgbox.setDefaultButton(bt_ok)
  3771. msgbox.exec_()
  3772. # work only if the notebook tab on focus is the Tools_Tab
  3773. if notebook_widget_name == 'tool_tab':
  3774. try:
  3775. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3776. except AttributeError:
  3777. return
  3778. # and only if the tool is NCC Tool
  3779. if tool_widget == self.ncclear_tool.toolName:
  3780. self.ncclear_tool.on_add_tool_by_key()
  3781. # and only if the tool is Paint Area Tool
  3782. elif tool_widget == self.paint_tool.toolName:
  3783. self.paint_tool.on_add_tool_by_key()
  3784. # and only if the tool is Solder Paste Dispensing Tool
  3785. elif tool_widget == self.paste_tool.toolName:
  3786. self.paste_tool.on_add_tool_by_key()
  3787. # and only if the tool is Isolation Tool
  3788. elif tool_widget == self.isolation_tool.toolName:
  3789. self.isolation_tool.on_add_tool_by_key()
  3790. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3791. # See description below.
  3792. def on_delete_keypress(self):
  3793. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3794. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3795. if notebook_widget_name == 'properties_tab':
  3796. if self.collection.get_active().kind == 'geometry':
  3797. self.collection.get_active().on_tool_delete()
  3798. # work only if the notebook tab on focus is the Tools_Tab
  3799. elif notebook_widget_name == 'tool_tab':
  3800. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3801. # and only if the tool is NCC Tool
  3802. if tool_widget == self.ncclear_tool.toolName:
  3803. self.ncclear_tool.on_tool_delete()
  3804. # and only if the tool is Paint Tool
  3805. elif tool_widget == self.paint_tool.toolName:
  3806. self.paint_tool.on_tool_delete()
  3807. # and only if the tool is Solder Paste Dispensing Tool
  3808. elif tool_widget == self.paste_tool.toolName:
  3809. self.paste_tool.on_tool_delete()
  3810. # and only if the tool is Isolation Tool
  3811. elif tool_widget == self.isolation_tool.toolName:
  3812. self.isolation_tool.on_tool_delete()
  3813. else:
  3814. self.on_delete()
  3815. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3816. # some screens you have to be careful where you hover with your mouse.
  3817. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3818. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3819. # Complicated, I know :)
  3820. def on_delete(self, force_deletion=False):
  3821. """
  3822. Delete the currently selected FlatCAMObjs.
  3823. :param force_deletion: used by Tcl command
  3824. :return: None
  3825. """
  3826. self.defaults.report_usage("on_delete()")
  3827. response = None
  3828. bt_ok = None
  3829. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3830. # a geometry object before we update it.
  3831. if self.call_source == 'app':
  3832. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3833. msgbox = QtWidgets.QMessageBox()
  3834. msgbox.setWindowTitle(_("Delete objects"))
  3835. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3836. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3837. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3838. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3839. "the selected objects?"))
  3840. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3841. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3842. msgbox.setDefaultButton(bt_ok)
  3843. msgbox.exec_()
  3844. response = msgbox.clickedButton()
  3845. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3846. response = bt_ok
  3847. if response == bt_ok:
  3848. if self.collection.get_active():
  3849. self.log.debug("App.on_delete()")
  3850. for obj_active in self.collection.get_selected():
  3851. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3852. if obj_active.kind == 'gerber':
  3853. obj_active.mark_shapes_storage.clear()
  3854. obj_active.mark_shapes.clear(update=True)
  3855. obj_active.mark_shapes.enabled = False
  3856. elif obj_active.kind == 'cncjob':
  3857. try:
  3858. obj_active.text_col.enabled = False
  3859. del obj_active.text_col
  3860. obj_active.annotation.clear(update=True)
  3861. del obj_active.annotation
  3862. obj_active.probing_shapes.clear(update=True)
  3863. except AttributeError as e:
  3864. self.log.debug(
  3865. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3866. )
  3867. while self.collection.get_selected():
  3868. self.delete_first_selected()
  3869. # make sure that the selection shape is deleted, too
  3870. self.delete_selection_shape()
  3871. # if there are no longer objects delete also the exclusion areas shapes
  3872. if not self.collection.get_list():
  3873. self.exc_areas.clear_shapes()
  3874. self.inform.emit('%s...' % _("Object(s) deleted"))
  3875. else:
  3876. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed."), _("No object is selected.")))
  3877. else:
  3878. self.inform.emit(_("Save the work in Editor and try again ..."))
  3879. def delete_first_selected(self):
  3880. # Keep this for later
  3881. try:
  3882. sel_obj = self.collection.get_active()
  3883. name = sel_obj.options["name"]
  3884. isPlotted = sel_obj.options["plot"]
  3885. except AttributeError:
  3886. self.log.debug("Nothing selected for deletion")
  3887. return
  3888. if self.is_legacy is True:
  3889. # Remove plot only if the object was plotted otherwise delaxes will fail
  3890. if isPlotted:
  3891. try:
  3892. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3893. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3894. except Exception as e:
  3895. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3896. self.plotcanvas.auto_adjust_axes()
  3897. # Remove from dictionary
  3898. self.collection.delete_active()
  3899. # Clear form
  3900. self.setup_default_properties_tab()
  3901. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3902. def on_set_origin(self):
  3903. """
  3904. Set the origin to the left mouse click position
  3905. :return: None
  3906. """
  3907. # display the message for the user
  3908. # and ask him to click on the desired position
  3909. self.defaults.report_usage("on_set_origin()")
  3910. def origin_replot():
  3911. def worker_task():
  3912. with self.proc_container.new('%s...' % _("Plotting")):
  3913. for obj in self.collection.get_list():
  3914. obj.plot()
  3915. self.plotcanvas.fit_view()
  3916. if self.is_legacy:
  3917. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3918. else:
  3919. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3920. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3921. self.inform.emit(_('Click to set the origin ...'))
  3922. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3923. # first disconnect it as it may have been used by something else
  3924. try:
  3925. self.replot_signal.disconnect()
  3926. except TypeError:
  3927. pass
  3928. self.replot_signal[list].connect(origin_replot)
  3929. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3930. """
  3931. :param event:
  3932. :param location:
  3933. :param noplot:
  3934. :param use_thread:
  3935. :return:
  3936. """
  3937. noplot_sig = noplot
  3938. def worker_task():
  3939. with self.proc_container.new(_("Setting Origin...")):
  3940. obj_list = self.collection.get_list()
  3941. for obj in obj_list:
  3942. obj.offset((x, y))
  3943. self.app_obj.object_changed.emit(obj)
  3944. # Update the object bounding box options
  3945. a, b, c, d = obj.bounds()
  3946. obj.options['xmin'] = a
  3947. obj.options['ymin'] = b
  3948. obj.options['xmax'] = c
  3949. obj.options['ymax'] = d
  3950. self.inform.emit('[success] %s...' % _('Origin set'))
  3951. for obj in obj_list:
  3952. out_name = obj.options["name"]
  3953. if obj.kind == 'gerber':
  3954. obj.source_file = self.f_handlers.export_gerber(
  3955. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3956. elif obj.kind == 'excellon':
  3957. obj.source_file = self.f_handlers.export_excellon(
  3958. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3959. if noplot_sig is False:
  3960. self.replot_signal.emit([])
  3961. if location is not None:
  3962. if len(location) != 2:
  3963. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3964. return 'fail'
  3965. x, y = location
  3966. if use_thread is True:
  3967. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3968. else:
  3969. worker_task()
  3970. self.should_we_save = True
  3971. return
  3972. if event is not None and event.button == 1:
  3973. if self.is_legacy is False:
  3974. event_pos = event.pos
  3975. else:
  3976. event_pos = (event.xdata, event.ydata)
  3977. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3978. if self.grid_status():
  3979. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3980. else:
  3981. pos = pos_canvas
  3982. x = 0 - pos[0]
  3983. y = 0 - pos[1]
  3984. if use_thread is True:
  3985. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3986. else:
  3987. worker_task()
  3988. self.should_we_save = True
  3989. def on_move2origin(self, use_thread=True):
  3990. """
  3991. Move selected objects to origin.
  3992. :param use_thread: Control if to use threaded operation. Boolean.
  3993. :return:
  3994. """
  3995. def worker_task():
  3996. with self.proc_container.new(_("Moving to Origin...")):
  3997. obj_list = self.collection.get_selected()
  3998. if not obj_list:
  3999. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4000. return
  4001. xminlist = []
  4002. yminlist = []
  4003. # first get a bounding box to fit all
  4004. for obj in obj_list:
  4005. xmin, ymin, xmax, ymax = obj.bounds()
  4006. xminlist.append(xmin)
  4007. yminlist.append(ymin)
  4008. # get the minimum x,y for all objects selected
  4009. x = min(xminlist)
  4010. y = min(yminlist)
  4011. for obj in obj_list:
  4012. obj.offset((-x, -y))
  4013. self.app_obj.object_changed.emit(obj)
  4014. # Update the object bounding box options
  4015. a, b, c, d = obj.bounds()
  4016. obj.options['xmin'] = a
  4017. obj.options['ymin'] = b
  4018. obj.options['xmax'] = c
  4019. obj.options['ymax'] = d
  4020. for obj in obj_list:
  4021. obj.plot()
  4022. for obj in obj_list:
  4023. out_name = obj.options["name"]
  4024. if obj.kind == 'gerber':
  4025. obj.source_file = self.f_handlers.export_gerber(
  4026. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4027. elif obj.kind == 'excellon':
  4028. obj.source_file = self.f_handlers.export_excellon(
  4029. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4030. self.inform.emit('[success] %s...' % _('Origin set'))
  4031. if use_thread is True:
  4032. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4033. else:
  4034. worker_task()
  4035. self.should_we_save = True
  4036. def on_jump_to(self, custom_location=None, fit_center=True):
  4037. """
  4038. Jump to a location by setting the mouse cursor location.
  4039. :param custom_location: Jump to a specified point. (x, y) tuple.
  4040. :param fit_center: If to fit view. Boolean.
  4041. :return:
  4042. """
  4043. self.defaults.report_usage("on_jump_to()")
  4044. if not custom_location:
  4045. dia_box_location = None
  4046. try:
  4047. dia_box_location = eval(self.clipboard.text())
  4048. except Exception:
  4049. pass
  4050. if type(dia_box_location) == tuple:
  4051. dia_box_location = str(dia_box_location)
  4052. else:
  4053. dia_box_location = None
  4054. # dia_box = Dialog_box(title=_("Jump to ..."),
  4055. # label=_("Enter the coordinates in format X,Y:"),
  4056. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4057. # initial_text=dia_box_location)
  4058. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4059. label=_("Enter the coordinates in format X,Y:"),
  4060. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4061. initial_text=dia_box_location,
  4062. reference=self.defaults['global_jump_ref'])
  4063. if dia_box.ok is True:
  4064. try:
  4065. location = eval(dia_box.location)
  4066. if not isinstance(location, tuple):
  4067. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4068. return
  4069. if dia_box.reference == 'rel':
  4070. rel_x = self.mouse[0] + location[0]
  4071. rel_y = self.mouse[1] + location[1]
  4072. location = (rel_x, rel_y)
  4073. self.defaults['global_jump_ref'] = dia_box.reference
  4074. except Exception:
  4075. return
  4076. else:
  4077. return
  4078. else:
  4079. location = custom_location
  4080. self.jump_signal.emit(location)
  4081. if fit_center:
  4082. self.plotcanvas.fit_center(loc=location)
  4083. cursor = QtGui.QCursor()
  4084. if self.is_legacy is False:
  4085. # I don't know where those differences come from but they are constant for the current
  4086. # execution of the application and they are multiples of a value around 0.0263mm.
  4087. # In a random way sometimes they are more sometimes they are less
  4088. # if units == 'MM':
  4089. # cal_factor = 0.0263
  4090. # else:
  4091. # cal_factor = 0.0263 / 25.4
  4092. cal_location = (location[0], location[1])
  4093. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4094. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4095. j_pos = (
  4096. int(canvas_origin.x() + round(jump_loc[0])),
  4097. int(canvas_origin.y() + round(jump_loc[1]))
  4098. )
  4099. cursor.setPos(j_pos[0], j_pos[1])
  4100. else:
  4101. # find the canvas origin which is in the top left corner
  4102. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4103. # determine the coordinates for the lowest left point of the canvas
  4104. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4105. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4106. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4107. # canvas) and the point (width, height) is in the top-right location
  4108. loc = self.plotcanvas.axes.transData.transform_point(location)
  4109. j_pos = (
  4110. int(x0 + loc[0]),
  4111. int(y0 - loc[1])
  4112. )
  4113. cursor.setPos(j_pos[0], j_pos[1])
  4114. self.plotcanvas.mouse = [location[0], location[1]]
  4115. if self.defaults["global_cursor_color_enabled"] is True:
  4116. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4117. else:
  4118. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4119. if self.grid_status():
  4120. # Update cursor
  4121. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4122. symbol='++', edge_color=self.cursor_color_3D,
  4123. edge_width=self.defaults["global_cursor_width"],
  4124. size=self.defaults["global_cursor_size"])
  4125. # Set the relative position label
  4126. dx = location[0] - float(self.rel_point1[0])
  4127. dy = location[1] - float(self.rel_point1[1])
  4128. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4129. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4130. # Set the position label
  4131. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4132. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4133. units = self.defaults["units"].lower()
  4134. self.plotcanvas.text_hud.text = \
  4135. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4136. dx, units, dy, units, location[0], units, location[1], units)
  4137. self.inform.emit('[success] %s' % _("Done."))
  4138. return location
  4139. def on_locate(self, obj, fit_center=True):
  4140. """
  4141. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4142. :param obj: The object on which to locate certain points
  4143. :param fit_center: If to fit view. Boolean.
  4144. :return: A point location. (x, y) tuple.
  4145. """
  4146. self.defaults.report_usage("on_locate()")
  4147. if obj is None:
  4148. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4149. return 'fail'
  4150. class DialogBoxChoice(QtWidgets.QDialog):
  4151. def __init__(self, title=None, icon=None, choice='bl'):
  4152. """
  4153. :param title: string with the window title
  4154. """
  4155. super(DialogBoxChoice, self).__init__()
  4156. self.ok = False
  4157. self.setWindowIcon(icon)
  4158. self.setWindowTitle(str(title))
  4159. self.form = QtWidgets.QFormLayout(self)
  4160. self.ref_radio = RadioSet([
  4161. {"label": _("Bottom Left"), "value": "bl"},
  4162. {"label": _("Top Left"), "value": "tl"},
  4163. {"label": _("Bottom Right"), "value": "br"},
  4164. {"label": _("Top Right"), "value": "tr"},
  4165. {"label": _("Center"), "value": "c"}
  4166. ], orientation='vertical', stretch=False)
  4167. self.ref_radio.set_value(choice)
  4168. self.form.addRow(self.ref_radio)
  4169. self.button_box = QtWidgets.QDialogButtonBox(
  4170. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4171. Qt.Horizontal, parent=self)
  4172. self.form.addRow(self.button_box)
  4173. self.button_box.accepted.connect(self.accept)
  4174. self.button_box.rejected.connect(self.reject)
  4175. if self.exec_() == QtWidgets.QDialog.Accepted:
  4176. self.ok = True
  4177. self.location_point = self.ref_radio.get_value()
  4178. else:
  4179. self.ok = False
  4180. self.location_point = None
  4181. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4182. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4183. choice=self.defaults['global_locate_pt'])
  4184. if dia_box.ok is True:
  4185. try:
  4186. location_point = dia_box.location_point
  4187. self.defaults['global_locate_pt'] = dia_box.location_point
  4188. except Exception:
  4189. return
  4190. else:
  4191. return
  4192. loc_b = obj.bounds()
  4193. if location_point == 'bl':
  4194. location = (loc_b[0], loc_b[1])
  4195. elif location_point == 'tl':
  4196. location = (loc_b[0], loc_b[3])
  4197. elif location_point == 'br':
  4198. location = (loc_b[2], loc_b[1])
  4199. elif location_point == 'tr':
  4200. location = (loc_b[2], loc_b[3])
  4201. else:
  4202. # center
  4203. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4204. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4205. location = (cx, cy)
  4206. self.locate_signal.emit(location, location_point)
  4207. if fit_center:
  4208. self.plotcanvas.fit_center(loc=location)
  4209. cursor = QtGui.QCursor()
  4210. if self.is_legacy is False:
  4211. # I don't know where those differences come from but they are constant for the current
  4212. # execution of the application and they are multiples of a value around 0.0263mm.
  4213. # In a random way sometimes they are more sometimes they are less
  4214. # if units == 'MM':
  4215. # cal_factor = 0.0263
  4216. # else:
  4217. # cal_factor = 0.0263 / 25.4
  4218. cal_location = (location[0], location[1])
  4219. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4220. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4221. j_pos = (
  4222. int(canvas_origin.x() + round(jump_loc[0])),
  4223. int(canvas_origin.y() + round(jump_loc[1]))
  4224. )
  4225. cursor.setPos(j_pos[0], j_pos[1])
  4226. else:
  4227. # find the canvas origin which is in the top left corner
  4228. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4229. # determine the coordinates for the lowest left point of the canvas
  4230. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4231. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4232. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4233. # canvas) and the point (width, height) is in the top-right location
  4234. loc = self.plotcanvas.axes.transData.transform_point(location)
  4235. j_pos = (
  4236. int(x0 + loc[0]),
  4237. int(y0 - loc[1])
  4238. )
  4239. cursor.setPos(j_pos[0], j_pos[1])
  4240. self.plotcanvas.mouse = [location[0], location[1]]
  4241. if self.defaults["global_cursor_color_enabled"] is True:
  4242. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4243. else:
  4244. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4245. if self.grid_status():
  4246. # Update cursor
  4247. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4248. symbol='++', edge_color=self.cursor_color_3D,
  4249. edge_width=self.defaults["global_cursor_width"],
  4250. size=self.defaults["global_cursor_size"])
  4251. # Set the relative position label
  4252. self.dx = location[0] - float(self.rel_point1[0])
  4253. self.dy = location[1] - float(self.rel_point1[1])
  4254. # Set the position label
  4255. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4256. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4257. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4258. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4259. units = self.defaults["units"].lower()
  4260. self.plotcanvas.text_hud.text = \
  4261. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4262. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4263. self.inform.emit('[success] %s' % _("Done."))
  4264. return location
  4265. def on_copy_command(self):
  4266. """
  4267. Will copy a selection of objects, creating new objects.
  4268. :return:
  4269. """
  4270. self.defaults.report_usage("on_copy_command()")
  4271. def initialize(obj_init, app_obj):
  4272. """
  4273. :param obj_init: the new object
  4274. :type obj_init: class
  4275. :param app_obj: An instance of the App class
  4276. :type app_obj: App
  4277. :return: None
  4278. :rtype:
  4279. """
  4280. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4281. try:
  4282. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4283. except AttributeError:
  4284. pass
  4285. try:
  4286. obj_init.apertures = deepcopy(obj.apertures)
  4287. except AttributeError:
  4288. pass
  4289. try:
  4290. if obj.tools:
  4291. obj_init.tools = deepcopy(obj.tools)
  4292. except Exception as err:
  4293. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4294. try:
  4295. obj_init.source_file = deepcopy(obj.source_file)
  4296. except (AttributeError, TypeError):
  4297. pass
  4298. def initialize_excellon(obj_init, app_obj):
  4299. obj_init.source_file = deepcopy(obj.source_file)
  4300. obj_init.tools = deepcopy(obj.tools)
  4301. # drills are offset, so they need to be deep copied
  4302. obj_init.drills = deepcopy(obj.drills)
  4303. # slots are offset, so they need to be deep copied
  4304. obj_init.slots = deepcopy(obj.slots)
  4305. obj_init.create_geometry()
  4306. if not obj_init.tools:
  4307. app_obj.debug("on_copy_command() --> no excellon tools")
  4308. return 'fail'
  4309. def initialize_script(obj_init, app_obj):
  4310. obj_init.source_file = deepcopy(obj.source_file)
  4311. def initialize_document(obj_init, app_obj):
  4312. obj_init.source_file = deepcopy(obj.source_file)
  4313. for obj in self.collection.get_selected():
  4314. obj_name = obj.options["name"]
  4315. try:
  4316. if isinstance(obj, ExcellonObject):
  4317. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4318. elif isinstance(obj, GerberObject):
  4319. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4320. elif isinstance(obj, GeometryObject):
  4321. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4322. elif isinstance(obj, ScriptObject):
  4323. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4324. elif isinstance(obj, DocumentObject):
  4325. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4326. except Exception as e:
  4327. return "Operation failed: %s" % str(e)
  4328. def on_copy_object2(self, custom_name):
  4329. def initialize_geometry(obj_init, app_obj):
  4330. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4331. try:
  4332. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4333. except AttributeError:
  4334. pass
  4335. try:
  4336. obj_init.apertures = deepcopy(obj.apertures)
  4337. except AttributeError:
  4338. pass
  4339. try:
  4340. if obj.tools:
  4341. obj_init.tools = deepcopy(obj.tools)
  4342. except Exception as ee:
  4343. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4344. def initialize_gerber(obj_init, app_obj):
  4345. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4346. obj_init.apertures = deepcopy(obj.apertures)
  4347. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4348. if not obj_init.apertures:
  4349. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4350. return 'fail'
  4351. def initialize_excellon(obj_init, app_obj):
  4352. obj_init.tools = deepcopy(obj.tools)
  4353. # drills are offset, so they need to be deep copied
  4354. obj_init.drills = deepcopy(obj.drills)
  4355. # slots are offset, so they need to be deep copied
  4356. obj_init.slots = deepcopy(obj.slots)
  4357. obj_init.create_geometry()
  4358. if not obj_init.tools:
  4359. app_obj.debug("on_copy_object2() --> no excellon tools")
  4360. return 'fail'
  4361. for obj in self.collection.get_selected():
  4362. obj_name = obj.options["name"]
  4363. try:
  4364. if isinstance(obj, ExcellonObject):
  4365. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4366. elif isinstance(obj, GerberObject):
  4367. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4368. elif isinstance(obj, GeometryObject):
  4369. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4370. except Exception as er:
  4371. return "Operation failed: %s" % str(er)
  4372. def on_rename_object(self, text):
  4373. """
  4374. Will rename an object.
  4375. :param text: New name for the object.
  4376. :return:
  4377. """
  4378. self.defaults.report_usage("on_rename_object()")
  4379. named_obj = self.collection.get_active()
  4380. for obj in named_obj:
  4381. if obj is list:
  4382. self.on_rename_object(text)
  4383. else:
  4384. try:
  4385. obj.options['name'] = text
  4386. except Exception as e:
  4387. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4388. def convert_any2geo(self):
  4389. """
  4390. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4391. :return:
  4392. """
  4393. self.defaults.report_usage("convert_any2geo()")
  4394. def initialize(obj_init, app):
  4395. obj_init.solid_geometry = obj.solid_geometry
  4396. try:
  4397. obj_init.follow_geometry = obj.follow_geometry
  4398. except AttributeError:
  4399. pass
  4400. try:
  4401. obj_init.apertures = obj.apertures
  4402. except AttributeError:
  4403. pass
  4404. try:
  4405. if obj.tools:
  4406. obj_init.tools = obj.tools
  4407. except AttributeError:
  4408. pass
  4409. def initialize_excellon(obj_init, app_obj):
  4410. # objs = self.collection.get_selected()
  4411. # GeometryObject.merge(objs, obj)
  4412. solid_geo = []
  4413. for tool in obj.tools:
  4414. for geo in obj.tools[tool]['solid_geometry']:
  4415. solid_geo.append(geo)
  4416. obj_init.solid_geometry = deepcopy(solid_geo)
  4417. if not obj_init.solid_geometry:
  4418. app_obj.log("convert_any2geo() failed")
  4419. return 'fail'
  4420. if not self.collection.get_selected():
  4421. log.warning("App.convert_any2geo --> No object selected")
  4422. self.inform.emit('[WARNING_NOTCL] %s' %
  4423. _("No object is selected."))
  4424. return
  4425. for obj in self.collection.get_selected():
  4426. obj_name = obj.options["name"]
  4427. try:
  4428. if obj.kind == 'excellon':
  4429. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4430. else:
  4431. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4432. except Exception as e:
  4433. return "Operation failed: %s" % str(e)
  4434. def convert_any2gerber(self):
  4435. """
  4436. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4437. :return:
  4438. """
  4439. def initialize_geometry(obj_init, app_obj):
  4440. apertures = {}
  4441. apid = 0
  4442. apertures[str(apid)] = {}
  4443. apertures[str(apid)]['geometry'] = []
  4444. for obj_orig in obj.solid_geometry:
  4445. new_elem = {'solid': obj_orig}
  4446. try:
  4447. new_elem['follow'] = obj_orig.exterior
  4448. except AttributeError:
  4449. pass
  4450. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4451. apertures[str(apid)]['size'] = 0.0
  4452. apertures[str(apid)]['type'] = 'C'
  4453. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4454. obj_init.apertures = deepcopy(apertures)
  4455. if not obj_init.apertures:
  4456. app_obj.log("convert_any2gerber() failed")
  4457. return 'fail'
  4458. def initialize_excellon(obj_init, app_obj):
  4459. apertures = {}
  4460. apid = 10
  4461. for tool in obj.tools:
  4462. apertures[str(apid)] = {}
  4463. apertures[str(apid)]['geometry'] = []
  4464. for geo in obj.tools[tool]['solid_geometry']:
  4465. new_el = {'solid': geo, 'follow': geo.exterior}
  4466. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4467. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4468. apertures[str(apid)]['type'] = 'C'
  4469. apid += 1
  4470. # create solid_geometry
  4471. solid_geometry = []
  4472. for apid in apertures:
  4473. for geo_el in apertures[apid]['geometry']:
  4474. solid_geometry.append(geo_el['solid'])
  4475. solid_geometry = MultiPolygon(solid_geometry)
  4476. solid_geometry = solid_geometry.buffer(0.0000001)
  4477. obj_init.solid_geometry = deepcopy(solid_geometry)
  4478. obj_init.apertures = deepcopy(apertures)
  4479. if not obj_init.apertures:
  4480. app_obj.log("convert_any2gerber() failed")
  4481. return 'fail'
  4482. if not self.collection.get_selected():
  4483. log.warning("App.convert_any2gerber --> No object selected")
  4484. self.inform.emit('[WARNING_NOTCL] %s' %
  4485. _("No object is selected."))
  4486. return
  4487. for obj in self.collection.get_selected():
  4488. obj_name = obj.options["name"]
  4489. try:
  4490. if obj.kind == 'excellon':
  4491. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4492. elif obj.kind == 'geometry':
  4493. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4494. else:
  4495. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4496. except Exception as e:
  4497. return "Operation failed: %s" % str(e)
  4498. def convert_any2excellon(self):
  4499. """
  4500. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4501. :return:
  4502. """
  4503. def initialize_geometry(obj_init, app_obj):
  4504. tools = {}
  4505. tooluid = 1
  4506. obj_init.solid_geometry = []
  4507. for geo in obj.solid_geometry:
  4508. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4509. continue
  4510. minx, miny, maxx, maxy = geo.bounds
  4511. new_dia = min([maxx-minx, maxy-miny])
  4512. new_drill = geo.centroid
  4513. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4514. current_tooldias = []
  4515. if tools:
  4516. for tool in tools:
  4517. if tools[tool] and 'tooldia' in tools[tool]:
  4518. current_tooldias.append(tools[tool]['tooldia'])
  4519. if new_dia in current_tooldias:
  4520. digits = app_obj.decimals
  4521. for tool in tools:
  4522. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4523. tools[tool]['drills'].append(new_drill)
  4524. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4525. else:
  4526. tools[tooluid] = {}
  4527. tools[tooluid]['tooldia'] = new_dia
  4528. tools[tooluid]['drills'] = [new_drill]
  4529. tools[tooluid]['slots'] = []
  4530. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4531. tooluid += 1
  4532. try:
  4533. obj_init.solid_geometry.append(new_drill_geo)
  4534. except (TypeError, AttributeError):
  4535. obj_init.solid_geometry = [new_drill_geo]
  4536. obj_init.tools = deepcopy(tools)
  4537. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4538. if not obj_init.solid_geometry:
  4539. return 'fail'
  4540. def initialize_gerber(obj_init, app_obj):
  4541. tools = {}
  4542. tooluid = 1
  4543. digits = app_obj.decimals
  4544. obj_init.solid_geometry = []
  4545. for apid in obj.apertures:
  4546. if 'geometry' in obj.apertures[apid]:
  4547. for geo_dict in obj.apertures[apid]['geometry']:
  4548. if 'follow' in geo_dict:
  4549. if isinstance(geo_dict['follow'], Point):
  4550. geo = geo_dict['solid']
  4551. minx, miny, maxx, maxy = geo.bounds
  4552. new_dia = min([maxx - minx, maxy - miny])
  4553. new_drill = geo.centroid
  4554. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4555. current_tooldias = []
  4556. if tools:
  4557. for tool in tools:
  4558. if tools[tool] and 'tooldia' in tools[tool]:
  4559. current_tooldias.append(
  4560. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4561. )
  4562. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4563. if formatted_new_dia in current_tooldias:
  4564. for tool in tools:
  4565. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4566. if new_drill not in tools[tool]['drills']:
  4567. tools[tool]['drills'].append(new_drill)
  4568. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4569. else:
  4570. tools[tooluid] = {}
  4571. tools[tooluid]['tooldia'] = new_dia
  4572. tools[tooluid]['drills'] = [new_drill]
  4573. tools[tooluid]['slots'] = []
  4574. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4575. tooluid += 1
  4576. try:
  4577. obj_init.solid_geometry.append(new_drill_geo)
  4578. except (TypeError, AttributeError):
  4579. obj_init.solid_geometry = [new_drill_geo]
  4580. elif isinstance(geo_dict['follow'], LineString):
  4581. geo_coords = list(geo_dict['follow'].coords)
  4582. # slots can have only a start and stop point and no intermediate points
  4583. if len(geo_coords) != 2:
  4584. continue
  4585. geo = geo_dict['solid']
  4586. try:
  4587. new_dia = obj.apertures[apid]['size']
  4588. except Exception:
  4589. continue
  4590. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4591. new_slot_geo = geo
  4592. current_tooldias = []
  4593. if tools:
  4594. for tool in tools:
  4595. if tools[tool] and 'tooldia' in tools[tool]:
  4596. current_tooldias.append(
  4597. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4598. )
  4599. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4600. for tool in tools:
  4601. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4602. '%.*f' % (self.decimals, new_dia)):
  4603. if new_slot not in tools[tool]['slots']:
  4604. tools[tool]['slots'].append(new_slot)
  4605. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4606. else:
  4607. tools[tooluid] = {}
  4608. tools[tooluid]['tooldia'] = new_dia
  4609. tools[tooluid]['drills'] = []
  4610. tools[tooluid]['slots'] = [new_slot]
  4611. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4612. tooluid += 1
  4613. try:
  4614. obj_init.solid_geometry.append(new_slot_geo)
  4615. except (TypeError, AttributeError):
  4616. obj_init.solid_geometry = [new_slot_geo]
  4617. obj_init.tools = deepcopy(tools)
  4618. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4619. if not obj_init.solid_geometry:
  4620. return 'fail'
  4621. if not self.collection.get_selected():
  4622. log.warning("App.convert_any2excellon--> No object selected")
  4623. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4624. return
  4625. for obj in self.collection.get_selected():
  4626. obj_name = obj.options["name"]
  4627. try:
  4628. if obj.kind == 'gerber':
  4629. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4630. elif obj.kind == 'geometry':
  4631. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4632. else:
  4633. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4634. except Exception as e:
  4635. return "Operation failed: %s" % str(e)
  4636. def abort_all_tasks(self):
  4637. """
  4638. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4639. on the first possible occasion.
  4640. :return:
  4641. """
  4642. if self.abort_flag is False:
  4643. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4644. self.abort_flag = True
  4645. self.cleanup.emit()
  4646. def app_is_idle(self):
  4647. if self.abort_flag:
  4648. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4649. self.abort_flag = False
  4650. def on_selectall(self):
  4651. """
  4652. Will draw a selection box shape around the selected objects.
  4653. :return:
  4654. """
  4655. self.defaults.report_usage("on_selectall()")
  4656. # delete the possible selection box around a possible selected object
  4657. self.delete_selection_shape()
  4658. for name in self.collection.get_names():
  4659. self.collection.set_active(name)
  4660. curr_sel_obj = self.collection.get_by_name(name)
  4661. # create the selection box around the selected object
  4662. if self.defaults['global_selection_shape'] is True:
  4663. self.draw_selection_shape(curr_sel_obj)
  4664. def on_toggle_preferences(self):
  4665. pref_open = False
  4666. for idx in range(self.ui.plot_tab_area.count()):
  4667. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4668. pref_open = True
  4669. if pref_open:
  4670. for idx in range(self.ui.plot_tab_area.count()):
  4671. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4672. self.ui.plot_tab_area.removeTab(idx)
  4673. break
  4674. self.ui.pref_status_label.setStyleSheet("")
  4675. else:
  4676. self.on_preferences()
  4677. def on_preferences(self):
  4678. """
  4679. Adds the Preferences in a Tab in Plot Area
  4680. :return:
  4681. """
  4682. # add the tab if it was closed
  4683. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4684. # delete the absolute and relative position and messages in the infobar
  4685. # self.ui.position_label.setText("")
  4686. # self.ui.rel_position_label.setText("")
  4687. # hide coordinates toolbars in the infobar while in DB
  4688. self.ui.coords_toolbar.hide()
  4689. self.ui.delta_coords_toolbar.hide()
  4690. # Switch plot_area to preferences page
  4691. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4692. # self.ui.show()
  4693. self.ui.pref_status_label.setStyleSheet("""
  4694. QLabel
  4695. {
  4696. color: black;
  4697. background-color: lightseagreen;
  4698. }
  4699. """
  4700. )
  4701. # detect changes in the preferences
  4702. for idx in range(self.ui.pref_tab_area.count()):
  4703. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4704. try:
  4705. try:
  4706. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4707. except (TypeError, AttributeError):
  4708. pass
  4709. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4710. except AttributeError:
  4711. pass
  4712. try:
  4713. try:
  4714. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4715. except (TypeError, AttributeError):
  4716. pass
  4717. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4718. except AttributeError:
  4719. pass
  4720. try:
  4721. try:
  4722. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4723. except (TypeError, AttributeError):
  4724. pass
  4725. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4726. except AttributeError:
  4727. pass
  4728. try:
  4729. try:
  4730. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4731. except (TypeError, AttributeError):
  4732. pass
  4733. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4734. except AttributeError:
  4735. pass
  4736. try:
  4737. try:
  4738. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4739. except (TypeError, AttributeError):
  4740. pass
  4741. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4742. except AttributeError:
  4743. pass
  4744. def on_tools_database(self, source='app'):
  4745. """
  4746. Adds the Tools Database in a Tab in Plot Area.
  4747. :return:
  4748. """
  4749. filename = self.tools_database_path()
  4750. # load the database tools from the file
  4751. try:
  4752. with open(filename) as f:
  4753. __ = f.read()
  4754. except Exception as eros:
  4755. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4756. log.error("Could not access tools DB file. The file may be locked,\n"
  4757. "not existing or doesn't have the read permissions.\n"
  4758. "Check to see if exists, it should be here: %s\n"
  4759. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4760. self.inform.emit('[ERROR] %s' % _("Could not load the file."))
  4761. return 'fail'
  4762. for idx in range(self.ui.plot_tab_area.count()):
  4763. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4764. # there can be only one instance of Tools Database at one time
  4765. return
  4766. if source == 'app':
  4767. self.tools_db_tab = ToolsDB2(
  4768. app=self,
  4769. parent=self.ui,
  4770. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4771. )
  4772. elif source == 'ncc':
  4773. self.tools_db_tab = ToolsDB2(
  4774. app=self,
  4775. parent=self.ui,
  4776. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4777. )
  4778. elif source == 'paint':
  4779. self.tools_db_tab = ToolsDB2(
  4780. app=self,
  4781. parent=self.ui,
  4782. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4783. )
  4784. elif source == 'iso':
  4785. self.tools_db_tab = ToolsDB2(
  4786. app=self,
  4787. parent=self.ui,
  4788. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4789. )
  4790. elif source == 'cutout':
  4791. self.tools_db_tab = ToolsDB2(
  4792. app=self,
  4793. parent=self.ui,
  4794. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4795. )
  4796. # add the tab if it was closed
  4797. try:
  4798. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4799. self.tools_db_tab.setObjectName("database_tab")
  4800. except Exception as e:
  4801. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4802. return
  4803. # delete the absolute and relative position and messages in the infobar
  4804. # self.ui.position_label.setText("")
  4805. # self.ui.rel_position_label.setText("")
  4806. # hide coordinates toolbars in the infobar while in DB
  4807. self.ui.coords_toolbar.hide()
  4808. self.ui.delta_coords_toolbar.hide()
  4809. # Switch plot_area to preferences page
  4810. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4811. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4812. self.tools_db_tab.ui_connect()
  4813. def on_geometry_tool_add_from_db_executed(self, tool):
  4814. """
  4815. Here add the tool from DB in the selected geometry object.
  4816. :return:
  4817. """
  4818. tool_from_db = deepcopy(tool)
  4819. obj = self.collection.get_active()
  4820. if obj.kind == 'geometry':
  4821. if tool['data']['tool_target'] not in [0, 1]: # General, Milling Type
  4822. # close the tab and delete it
  4823. for idx in range(self.ui.plot_tab_area.count()):
  4824. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4825. wdg = self.ui.plot_tab_area.widget(idx)
  4826. wdg.deleteLater()
  4827. self.ui.plot_tab_area.removeTab(idx)
  4828. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4829. return
  4830. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4831. # close the tab and delete it
  4832. for idx in range(self.ui.plot_tab_area.count()):
  4833. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4834. wdg = self.ui.plot_tab_area.widget(idx)
  4835. wdg.deleteLater()
  4836. self.ui.plot_tab_area.removeTab(idx)
  4837. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4838. elif obj.kind == 'gerber':
  4839. if tool['data']['tool_target'] not in [0, 3]: # General, Isolation Type
  4840. # close the tab and delete it
  4841. for idx in range(self.ui.plot_tab_area.count()):
  4842. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4843. wdg = self.ui.plot_tab_area.widget(idx)
  4844. wdg.deleteLater()
  4845. self.ui.plot_tab_area.removeTab(idx)
  4846. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4847. return
  4848. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4849. # close the tab and delete it
  4850. for idx in range(self.ui.plot_tab_area.count()):
  4851. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4852. wdg = self.ui.plot_tab_area.widget(idx)
  4853. wdg.deleteLater()
  4854. self.ui.plot_tab_area.removeTab(idx)
  4855. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4856. else:
  4857. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4858. def on_plot_area_tab_closed(self, tab_obj_name):
  4859. """
  4860. Executed whenever a QTab is closed in the Plot Area.
  4861. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4862. :return:
  4863. """
  4864. if tab_obj_name == "preferences_tab":
  4865. self.preferencesUiManager.on_close_preferences_tab()
  4866. elif tab_obj_name == "database_tab":
  4867. # disconnect the signals from the table widget in tab
  4868. self.tools_db_tab.ui_disconnect()
  4869. if self.tools_db_changed_flag is True:
  4870. msgbox = QtWidgets.QMessageBox()
  4871. msgbox.setText(_("One or more Tools are edited.\n"
  4872. "Do you want to update the Tools Database?"))
  4873. msgbox.setWindowTitle(_("Save Tools Database"))
  4874. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4875. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4876. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4877. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4878. msgbox.setDefaultButton(bt_yes)
  4879. msgbox.exec_()
  4880. response = msgbox.clickedButton()
  4881. if response == bt_yes:
  4882. self.tools_db_tab.on_save_tools_db()
  4883. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4884. else:
  4885. self.tools_db_changed_flag = False
  4886. self.inform.emit('')
  4887. return
  4888. self.tools_db_tab.deleteLater()
  4889. elif tab_obj_name == "text_editor_tab":
  4890. self.toggle_codeeditor = False
  4891. elif tab_obj_name == "bookmarks_tab":
  4892. self.book_dialog_tab.rebuild_actions()
  4893. self.book_dialog_tab.deleteLater()
  4894. else:
  4895. pass
  4896. # restore the coords toolbars
  4897. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4898. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4899. def on_flipy(self):
  4900. """
  4901. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4902. :return:
  4903. """
  4904. self.defaults.report_usage("on_flipy()")
  4905. obj_list = self.collection.get_selected()
  4906. xminlist = []
  4907. yminlist = []
  4908. xmaxlist = []
  4909. ymaxlist = []
  4910. if not obj_list:
  4911. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4912. else:
  4913. try:
  4914. # first get a bounding box to fit all
  4915. for obj in obj_list:
  4916. xmin, ymin, xmax, ymax = obj.bounds()
  4917. xminlist.append(xmin)
  4918. yminlist.append(ymin)
  4919. xmaxlist.append(xmax)
  4920. ymaxlist.append(ymax)
  4921. # get the minimum x,y and maximum x,y for all objects selected
  4922. xminimal = min(xminlist)
  4923. yminimal = min(yminlist)
  4924. xmaximal = max(xmaxlist)
  4925. ymaximal = max(ymaxlist)
  4926. px = 0.5 * (xminimal + xmaximal)
  4927. py = 0.5 * (yminimal + ymaximal)
  4928. # execute mirroring
  4929. for obj in obj_list:
  4930. obj.mirror('X', [px, py])
  4931. obj.plot()
  4932. self.app_obj.object_changed.emit(obj)
  4933. self.inform.emit('[success] %s.' % _("Flip on Y axis done"))
  4934. except Exception as e:
  4935. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  4936. return
  4937. def on_flipx(self):
  4938. """
  4939. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4940. :return:
  4941. """
  4942. self.defaults.report_usage("on_flipx()")
  4943. obj_list = self.collection.get_selected()
  4944. xminlist = []
  4945. yminlist = []
  4946. xmaxlist = []
  4947. ymaxlist = []
  4948. if not obj_list:
  4949. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4950. else:
  4951. try:
  4952. # first get a bounding box to fit all
  4953. for obj in obj_list:
  4954. xmin, ymin, xmax, ymax = obj.bounds()
  4955. xminlist.append(xmin)
  4956. yminlist.append(ymin)
  4957. xmaxlist.append(xmax)
  4958. ymaxlist.append(ymax)
  4959. # get the minimum x,y and maximum x,y for all objects selected
  4960. xminimal = min(xminlist)
  4961. yminimal = min(yminlist)
  4962. xmaximal = max(xmaxlist)
  4963. ymaximal = max(ymaxlist)
  4964. px = 0.5 * (xminimal + xmaximal)
  4965. py = 0.5 * (yminimal + ymaximal)
  4966. # execute mirroring
  4967. for obj in obj_list:
  4968. obj.mirror('Y', [px, py])
  4969. obj.plot()
  4970. self.app_obj.object_changed.emit(obj)
  4971. self.inform.emit('[success] %s.' % _("Flip on X axis done"))
  4972. except Exception as e:
  4973. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  4974. return
  4975. def on_rotate(self, silent=False, preset=None):
  4976. """
  4977. Executed when Options -> Rotate Selection menu entry is clicked.
  4978. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4979. :param preset: A value to be used as predefined angle for rotation.
  4980. :return:
  4981. """
  4982. self.defaults.report_usage("on_rotate()")
  4983. obj_list = self.collection.get_selected()
  4984. xminlist = []
  4985. yminlist = []
  4986. xmaxlist = []
  4987. ymaxlist = []
  4988. if not obj_list:
  4989. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  4990. else:
  4991. if silent is False:
  4992. rotatebox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  4993. min=-360, max=360, decimals=4,
  4994. init_val=float(self.defaults['tools_transform_rotate']),
  4995. parent=self.ui)
  4996. rotatebox.setWindowIcon(QtGui.QIcon(self.resource_location + '/rotate.png'))
  4997. num, ok = rotatebox.get_value()
  4998. else:
  4999. num = preset
  5000. ok = True
  5001. if ok:
  5002. try:
  5003. # first get a bounding box to fit all
  5004. for obj in obj_list:
  5005. xmin, ymin, xmax, ymax = obj.bounds()
  5006. xminlist.append(xmin)
  5007. yminlist.append(ymin)
  5008. xmaxlist.append(xmax)
  5009. ymaxlist.append(ymax)
  5010. # get the minimum x,y and maximum x,y for all objects selected
  5011. xminimal = min(xminlist)
  5012. yminimal = min(yminlist)
  5013. xmaximal = max(xmaxlist)
  5014. ymaximal = max(ymaxlist)
  5015. px = 0.5 * (xminimal + xmaximal)
  5016. py = 0.5 * (yminimal + ymaximal)
  5017. for sel_obj in obj_list:
  5018. sel_obj.rotate(-float(num), point=(px, py))
  5019. sel_obj.plot()
  5020. self.app_obj.object_changed.emit(sel_obj)
  5021. self.inform.emit('[success] %s' % _("Rotation done."))
  5022. except Exception as e:
  5023. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5024. return
  5025. def on_skewx(self):
  5026. """
  5027. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5028. :return:
  5029. """
  5030. self.defaults.report_usage("on_skewx()")
  5031. obj_list = self.collection.get_selected()
  5032. xminlist = []
  5033. yminlist = []
  5034. if not obj_list:
  5035. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5036. else:
  5037. skewxbox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  5038. min=-360, max=360, decimals=4,
  5039. init_val=float(self.defaults['tools_transform_skew_x']),
  5040. parent=self.ui)
  5041. skewxbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/skewX.png'))
  5042. num, ok = skewxbox.get_value()
  5043. if ok:
  5044. # first get a bounding box to fit all
  5045. for obj in obj_list:
  5046. xmin, ymin, xmax, ymax = obj.bounds()
  5047. xminlist.append(xmin)
  5048. yminlist.append(ymin)
  5049. # get the minimum x,y and maximum x,y for all objects selected
  5050. xminimal = min(xminlist)
  5051. yminimal = min(yminlist)
  5052. for obj in obj_list:
  5053. obj.skew(num, 0, point=(xminimal, yminimal))
  5054. obj.plot()
  5055. self.app_obj.object_changed.emit(obj)
  5056. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  5057. def on_skewy(self):
  5058. """
  5059. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5060. :return:
  5061. """
  5062. self.defaults.report_usage("on_skewy()")
  5063. obj_list = self.collection.get_selected()
  5064. xminlist = []
  5065. yminlist = []
  5066. if not obj_list:
  5067. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5068. else:
  5069. skewybox = FCInputDoubleSpinner(title=_("Transform"), text=_("Enter the Angle value:"),
  5070. min=-360, max=360, decimals=4,
  5071. init_val=float(self.defaults['tools_transform_skew_y']),
  5072. parent=self.ui)
  5073. skewybox.setWindowIcon(QtGui.QIcon(self.resource_location + '/skewY.png'))
  5074. num, ok = skewybox.get_value()
  5075. if ok:
  5076. # first get a bounding box to fit all
  5077. for obj in obj_list:
  5078. xmin, ymin, xmax, ymax = obj.bounds()
  5079. xminlist.append(xmin)
  5080. yminlist.append(ymin)
  5081. # get the minimum x,y and maximum x,y for all objects selected
  5082. xminimal = min(xminlist)
  5083. yminimal = min(yminlist)
  5084. for obj in obj_list:
  5085. obj.skew(0, num, point=(xminimal, yminimal))
  5086. obj.plot()
  5087. self.app_obj.object_changed.emit(obj)
  5088. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  5089. def on_plots_updated(self):
  5090. """
  5091. Callback used to report when the plots have changed.
  5092. Adjust axes and zooms to fit.
  5093. :return: None
  5094. """
  5095. if self.is_legacy is False:
  5096. self.plotcanvas.update()
  5097. else:
  5098. self.plotcanvas.auto_adjust_axes()
  5099. self.on_zoom_fit()
  5100. self.collection.update_view()
  5101. # self.inform.emit(_("Plots updated ..."))
  5102. def on_toolbar_replot(self):
  5103. """
  5104. Callback for toolbar button. Re-plots all objects.
  5105. :return: None
  5106. """
  5107. self.log.debug("on_toolbar_replot()")
  5108. try:
  5109. obj = self.collection.get_active()
  5110. if obj:
  5111. obj.read_form()
  5112. else:
  5113. self.on_zoom_fit()
  5114. except AttributeError as e:
  5115. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  5116. pass
  5117. self.plot_all()
  5118. def grid_status(self):
  5119. return True if self.ui.grid_snap_btn.isChecked() else False
  5120. def populate_cmenu_grids(self):
  5121. units = self.defaults['units'].lower()
  5122. # for act in self.ui.cmenu_gridmenu.actions():
  5123. # act.triggered.disconnect()
  5124. self.ui.cmenu_gridmenu.clear()
  5125. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5126. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5127. _("Grid On/Off"))
  5128. grid_toggle.setCheckable(True)
  5129. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5130. self.ui.cmenu_gridmenu.addSeparator()
  5131. for grid in sorted_list:
  5132. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5133. "%s" % str(grid))
  5134. action.triggered.connect(self.set_grid)
  5135. self.ui.cmenu_gridmenu.addSeparator()
  5136. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5137. _("Add"))
  5138. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5139. _("Delete"))
  5140. grid_add.triggered.connect(self.on_grid_add)
  5141. grid_delete.triggered.connect(self.on_grid_delete)
  5142. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5143. def set_grid(self):
  5144. menu_action = self.sender()
  5145. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5146. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5147. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5148. def on_grid_add(self):
  5149. # ## Current application units in lower Case
  5150. units = self.defaults['units'].lower()
  5151. grid_add_popup = FCInputDoubleSpinner(title=_("New Grid ..."),
  5152. text=_('Enter a Grid Value:'),
  5153. min=0.0000, max=99.9999, decimals=self.decimals,
  5154. parent=self.ui)
  5155. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5156. val, ok = grid_add_popup.get_value()
  5157. if ok:
  5158. if float(val) == 0:
  5159. self.inform.emit('[WARNING_NOTCL] %s' %
  5160. _("Please enter a grid value with non-zero value, in Float format."))
  5161. return
  5162. else:
  5163. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5164. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5165. self.inform.emit('[success] %s...' % _("New Grid added"))
  5166. else:
  5167. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5168. else:
  5169. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5170. def on_grid_delete(self):
  5171. # ## Current application units in lower Case
  5172. units = self.defaults['units'].lower()
  5173. grid_del_popup = FCInputDoubleSpinner(title="Delete Grid ...",
  5174. text='Enter a Grid Value:',
  5175. min=0.0000, max=99.9999, decimals=self.decimals,
  5176. parent=self.ui)
  5177. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5178. val, ok = grid_del_popup.get_value()
  5179. if ok:
  5180. if float(val) == 0:
  5181. self.inform.emit('[WARNING_NOTCL] %s' %
  5182. _("Please enter a grid value with non-zero value, in Float format."))
  5183. return
  5184. else:
  5185. try:
  5186. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5187. except ValueError:
  5188. self.inform.emit('[ERROR_NOTCL]%s...' % _("Grid Value does not exist"))
  5189. return
  5190. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5191. else:
  5192. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5193. def on_shortcut_list(self):
  5194. self.defaults.report_usage("on_shortcut_list()")
  5195. # add the tab if it was closed
  5196. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5197. # delete the absolute and relative position and messages in the infobar
  5198. # self.ui.position_label.setText("")
  5199. # self.ui.rel_position_label.setText("")
  5200. # hide coordinates toolbars in the infobar while in DB
  5201. self.ui.coords_toolbar.hide()
  5202. self.ui.delta_coords_toolbar.hide()
  5203. # Switch plot_area to preferences page
  5204. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5205. # self.ui.show()
  5206. def on_select_tab(self, name):
  5207. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5208. if self.ui.splitter.sizes()[0] == 0:
  5209. self.ui.splitter.setSizes([1, 1])
  5210. else:
  5211. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5212. self.ui.splitter.setSizes([0, 1])
  5213. if name == 'project':
  5214. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5215. elif name == 'properties':
  5216. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5217. elif name == 'tool':
  5218. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5219. def on_copy_name(self):
  5220. self.defaults.report_usage("on_copy_name()")
  5221. obj = self.collection.get_active()
  5222. try:
  5223. name = obj.options["name"]
  5224. except AttributeError:
  5225. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5226. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  5227. return
  5228. self.clipboard.setText(name)
  5229. self.inform.emit(_("Name copied to clipboard ..."))
  5230. def on_mouse_click_over_plot(self, event):
  5231. """
  5232. Default actions are:
  5233. :param event: Contains information about the event, like which button
  5234. was clicked, the pixel coordinates and the axes coordinates.
  5235. :return: None
  5236. """
  5237. self.pos = []
  5238. if self.is_legacy is False:
  5239. event_pos = event.pos
  5240. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5241. # # Set the mouse button for panning
  5242. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5243. else:
  5244. event_pos = (event.xdata, event.ydata)
  5245. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5246. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5247. # So it can receive key presses
  5248. self.plotcanvas.native.setFocus()
  5249. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5250. if self.grid_status():
  5251. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5252. else:
  5253. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5254. try:
  5255. if event.button == 1:
  5256. # Reset here the relative coordinates so there is a new reference on the click position
  5257. if self.rel_point1 is None:
  5258. self.rel_point1 = self.pos
  5259. else:
  5260. self.rel_point2 = copy(self.rel_point1)
  5261. self.rel_point1 = self.pos
  5262. self.on_mouse_move_over_plot(event, origin_click=True)
  5263. except Exception as e:
  5264. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5265. def on_mouse_double_click_over_plot(self, event):
  5266. if event.button == 1:
  5267. self.doubleclick = True
  5268. def on_mouse_move_over_plot(self, event, origin_click=None):
  5269. """
  5270. Callback for the mouse motion event over the plot.
  5271. :param event: Contains information about the event.
  5272. :param origin_click
  5273. :return: None
  5274. """
  5275. if self.is_legacy is False:
  5276. event_pos = event.pos
  5277. if self.defaults["global_pan_button"] == '2':
  5278. pan_button = 2
  5279. else:
  5280. pan_button = 3
  5281. self.event_is_dragging = event.is_dragging
  5282. else:
  5283. event_pos = (event.xdata, event.ydata)
  5284. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5285. if self.defaults["global_pan_button"] == '2':
  5286. pan_button = 3
  5287. else:
  5288. pan_button = 2
  5289. self.event_is_dragging = self.plotcanvas.is_dragging
  5290. # So it can receive key presses but not when the Tcl Shell is active
  5291. if not self.ui.shell_dock.isVisible():
  5292. if not self.plotcanvas.native.hasFocus():
  5293. self.plotcanvas.native.setFocus()
  5294. self.pos_jump = event_pos
  5295. self.ui.popMenu.mouse_is_panning = False
  5296. if origin_click is None:
  5297. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5298. if event.button == pan_button and self.event_is_dragging == 1:
  5299. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5300. if self.ui.popMenu.popup_active:
  5301. self.ui.popMenu.popup_active = False
  5302. return
  5303. self.ui.popMenu.mouse_is_panning = True
  5304. return
  5305. if self.rel_point1 is not None:
  5306. try: # May fail in case mouse not within axes
  5307. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5308. if pos_canvas[0] is None or pos_canvas[1] is None:
  5309. return
  5310. if self.grid_status():
  5311. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5312. # Update cursor
  5313. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5314. symbol='++', edge_color=self.cursor_color_3D,
  5315. edge_width=self.defaults["global_cursor_width"],
  5316. size=self.defaults["global_cursor_size"])
  5317. else:
  5318. pos = (pos_canvas[0], pos_canvas[1])
  5319. self.dx = pos[0] - float(self.rel_point1[0])
  5320. self.dy = pos[1] - float(self.rel_point1[1])
  5321. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5322. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5323. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5324. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5325. units = self.defaults["units"].lower()
  5326. self.plotcanvas.text_hud.text = \
  5327. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5328. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5329. self.mouse = [pos[0], pos[1]]
  5330. if self.defaults['global_selection_shape'] is False:
  5331. self.selection_type = None
  5332. return
  5333. # if the mouse is moved and the LMB is clicked then the action is a selection
  5334. if self.event_is_dragging == 1 and event.button == 1:
  5335. self.delete_selection_shape()
  5336. if self.dx < 0:
  5337. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5338. face_color=self.defaults['global_alt_sel_fill'])
  5339. self.selection_type = False
  5340. elif self.dx >= 0:
  5341. self.draw_moving_selection_shape(self.pos, pos)
  5342. self.selection_type = True
  5343. else:
  5344. self.selection_type = None
  5345. else:
  5346. self.selection_type = None
  5347. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5348. if self.defaults['global_hover']:
  5349. for obj in self.collection.get_list():
  5350. try:
  5351. # select the object(s) only if it is enabled (plotted)
  5352. if obj.options['plot']:
  5353. if obj not in self.collection.get_selected():
  5354. poly_obj = Polygon(
  5355. [(obj.options['xmin'], obj.options['ymin']),
  5356. (obj.options['xmax'], obj.options['ymin']),
  5357. (obj.options['xmax'], obj.options['ymax']),
  5358. (obj.options['xmin'], obj.options['ymax'])]
  5359. )
  5360. if Point(pos).within(poly_obj):
  5361. if obj.isHovering is False:
  5362. obj.isHovering = True
  5363. obj.notHovering = True
  5364. # create the selection box around the selected object
  5365. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5366. else:
  5367. if obj.notHovering is True:
  5368. obj.notHovering = False
  5369. obj.isHovering = False
  5370. self.delete_hover_shape()
  5371. except Exception:
  5372. # the Exception here will happen if we try to select on screen and we have an
  5373. # newly (and empty) just created Geometry or Excellon object that do not have the
  5374. # xmin, xmax, ymin, ymax options.
  5375. # In this case poly_obj creation (see above) will fail
  5376. pass
  5377. except Exception as e:
  5378. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5379. self.ui.position_label.setText("")
  5380. self.ui.rel_position_label.setText("")
  5381. self.mouse = None
  5382. def on_mouse_click_release_over_plot(self, event):
  5383. """
  5384. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5385. and has been registered in ''self.__init__()''.
  5386. :param event: contains information about the event.
  5387. :return:
  5388. """
  5389. if self.is_legacy is False:
  5390. event_pos = event.pos
  5391. right_button = 2
  5392. else:
  5393. event_pos = (event.xdata, event.ydata)
  5394. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5395. right_button = 3
  5396. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5397. if self.grid_status():
  5398. try:
  5399. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5400. except TypeError:
  5401. return
  5402. else:
  5403. pos = (pos_canvas[0], pos_canvas[1])
  5404. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5405. # canvas menu
  5406. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5407. self.ui.popMenu.mouse_is_panning = False
  5408. self.cursor = QtGui.QCursor()
  5409. self.populate_cmenu_grids()
  5410. self.ui.popMenu.popup(self.cursor.pos())
  5411. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5412. # selection and then select a type of selection ("enclosing" or "touching")
  5413. if event.button == 1: # left click
  5414. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5415. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5416. if modifiers == QtCore.Qt.ShiftModifier:
  5417. # do not auto open the Project Tab
  5418. self.click_noproject = True
  5419. self.clipboard.setText(
  5420. self.defaults["global_point_clipboard_format"] %
  5421. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5422. )
  5423. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5424. return
  5425. # the object selection on canvas does not work for App Tools or for Editors
  5426. if self.call_source != 'app':
  5427. return
  5428. if self.doubleclick is True:
  5429. self.doubleclick = False
  5430. if self.collection.get_selected():
  5431. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5432. if self.ui.splitter.sizes()[0] == 0:
  5433. self.ui.splitter.setSizes([1, 1])
  5434. try:
  5435. # delete the selection shape(S) as it may be in the way
  5436. self.delete_selection_shape()
  5437. self.delete_hover_shape()
  5438. except Exception as e:
  5439. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5440. return
  5441. else:
  5442. # WORKAROUND for LEGACY MODE
  5443. if self.is_legacy is True:
  5444. # if there is no move on canvas then we have no dragging selection
  5445. if self.dx == 0 or self.dy == 0:
  5446. self.selection_type = None
  5447. if self.selection_type is not None:
  5448. try:
  5449. self.selection_area_handler(self.pos, pos, self.selection_type)
  5450. self.selection_type = None
  5451. except Exception as e:
  5452. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5453. return
  5454. else:
  5455. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5456. if key_modifier == QtCore.Qt.ShiftModifier:
  5457. mod_key = 'Shift'
  5458. elif key_modifier == QtCore.Qt.ControlModifier:
  5459. mod_key = 'Control'
  5460. else:
  5461. mod_key = None
  5462. try:
  5463. if self.command_active is None:
  5464. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5465. # deselect, and if it's not selected then it will be selected
  5466. # If there is no active command (self.command_active is None) then we check if we clicked
  5467. # on a object by checking the bounding limits against mouse click position
  5468. if mod_key == self.defaults["global_mselect_key"]:
  5469. self.select_objects(key='multisel')
  5470. else:
  5471. # If there is no active command (self.command_active is None) then we check if
  5472. # we clicked on a object by checking the bounding limits against mouse click position
  5473. self.select_objects()
  5474. self.delete_hover_shape()
  5475. except Exception as e:
  5476. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5477. return
  5478. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5479. """
  5480. :param start_pos: mouse position when the selection LMB click was done
  5481. :param end_pos: mouse position when the left mouse button is released
  5482. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5483. :return:
  5484. """
  5485. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5486. # delete previous selection shape
  5487. self.delete_selection_shape()
  5488. # make all objects inactive
  5489. self.collection.set_all_inactive()
  5490. for obj in self.collection.get_list():
  5491. try:
  5492. # select the object(s) only if it is enabled (plotted)
  5493. if obj.options['plot']:
  5494. # it's a line without area
  5495. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5496. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5497. # it's a geometry with area
  5498. else:
  5499. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5500. (obj.options['xmax'], obj.options['ymin']),
  5501. (obj.options['xmax'], obj.options['ymax']),
  5502. (obj.options['xmin'], obj.options['ymax'])])
  5503. if poly_obj.is_empty or not poly_obj.is_valid:
  5504. continue
  5505. if sel_type is True:
  5506. if poly_obj.within(poly_selection):
  5507. # create the selection box around the selected object
  5508. if self.defaults['global_selection_shape'] is True:
  5509. self.draw_selection_shape(obj)
  5510. self.collection.set_active(obj.options['name'])
  5511. else:
  5512. if poly_selection.intersects(poly_obj):
  5513. # create the selection box around the selected object
  5514. if self.defaults['global_selection_shape'] is True:
  5515. self.draw_selection_shape(obj)
  5516. self.collection.set_active(obj.options['name'])
  5517. obj.selection_shape_drawn = True
  5518. except Exception as e:
  5519. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5520. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5521. # In this case poly_obj creation (see above) will fail
  5522. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5523. def select_objects(self, key=None):
  5524. """
  5525. Will select objects clicked on canvas
  5526. :param key: for future use in cumulative selection
  5527. :return:
  5528. """
  5529. # list where we store the overlapped objects under our mouse left click position
  5530. if key is None:
  5531. self.objects_under_the_click_list = []
  5532. # Populate the list with the overlapped objects on the click position
  5533. curr_x, curr_y = self.pos
  5534. for obj in self.all_objects_list:
  5535. # ScriptObject and DocumentObject objects can't be selected
  5536. if obj.kind == 'script' or obj.kind == 'document':
  5537. continue
  5538. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5539. continue
  5540. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5541. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5542. if obj.options['name'] not in self.objects_under_the_click_list:
  5543. if obj.options['plot']:
  5544. # add objects to the objects_under_the_click list only if the object is plotted
  5545. # (active and not disabled)
  5546. self.objects_under_the_click_list.append(obj.options['name'])
  5547. try:
  5548. if self.objects_under_the_click_list:
  5549. curr_sel_obj = self.collection.get_active()
  5550. # case when there is only an object under the click and we toggle it
  5551. if len(self.objects_under_the_click_list) == 1:
  5552. if curr_sel_obj is None:
  5553. self.collection.set_active(self.objects_under_the_click_list[0])
  5554. curr_sel_obj = self.collection.get_active()
  5555. # create the selection box around the selected object
  5556. if self.defaults['global_selection_shape'] is True:
  5557. self.draw_selection_shape(curr_sel_obj)
  5558. curr_sel_obj.selection_shape_drawn = True
  5559. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5560. self.collection.on_objects_selection(False)
  5561. self.delete_selection_shape()
  5562. curr_sel_obj.selection_shape_drawn = False
  5563. self.collection.set_active(self.objects_under_the_click_list[0])
  5564. curr_sel_obj = self.collection.get_active()
  5565. # create the selection box around the selected object
  5566. if self.defaults['global_selection_shape'] is True:
  5567. self.draw_selection_shape(curr_sel_obj)
  5568. curr_sel_obj.selection_shape_drawn = True
  5569. self.selected_message(curr_sel_obj=curr_sel_obj)
  5570. elif curr_sel_obj.selection_shape_drawn is False:
  5571. if self.defaults['global_selection_shape'] is True:
  5572. self.draw_selection_shape(curr_sel_obj)
  5573. curr_sel_obj.selection_shape_drawn = True
  5574. else:
  5575. self.collection.on_objects_selection(False)
  5576. self.delete_selection_shape()
  5577. if self.call_source != 'app':
  5578. self.call_source = 'app'
  5579. self.selected_message(curr_sel_obj=curr_sel_obj)
  5580. else:
  5581. # If there is no selected object
  5582. # make active the first element of the overlapped objects list
  5583. if self.collection.get_active() is None:
  5584. self.collection.set_active(self.objects_under_the_click_list[0])
  5585. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5586. name_sel_obj = self.collection.get_active().options['name']
  5587. # In case that there is a selected object but it is not in the overlapped object list
  5588. # make that object inactive and activate the first element in the overlapped object list
  5589. if name_sel_obj not in self.objects_under_the_click_list:
  5590. self.collection.set_inactive(name_sel_obj)
  5591. name_sel_obj = self.objects_under_the_click_list[0]
  5592. self.collection.set_active(name_sel_obj)
  5593. else:
  5594. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5595. self.collection.set_all_inactive()
  5596. self.collection.set_active(
  5597. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5598. curr_sel_obj = self.collection.get_active()
  5599. # delete the possible selection box around a possible selected object
  5600. self.delete_selection_shape()
  5601. curr_sel_obj.selection_shape_drawn = False
  5602. # create the selection box around the selected object
  5603. if self.defaults['global_selection_shape'] is True:
  5604. self.draw_selection_shape(curr_sel_obj)
  5605. curr_sel_obj.selection_shape_drawn = True
  5606. self.selected_message(curr_sel_obj=curr_sel_obj)
  5607. else:
  5608. # deselect everything
  5609. self.collection.on_objects_selection(False)
  5610. # delete the possible selection box around a possible selected object
  5611. self.delete_selection_shape()
  5612. for o in self.collection.get_list():
  5613. o.selection_shape_drawn = False
  5614. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5615. # only when working on App
  5616. if self.call_source == 'app':
  5617. if self.click_noproject is False:
  5618. # if the Tool Tab is in focus don't change focus to Project Tab
  5619. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5620. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5621. else:
  5622. # restore auto open the Project Tab
  5623. self.click_noproject = False
  5624. # delete any text in the status bar, implicitly the last object name that was selected
  5625. # self.inform.emit("")
  5626. else:
  5627. self.call_source = 'app'
  5628. except Exception as e:
  5629. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5630. def selected_message(self, curr_sel_obj):
  5631. if curr_sel_obj:
  5632. if curr_sel_obj.kind == 'gerber':
  5633. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5634. color='green',
  5635. name=str(curr_sel_obj.options['name']),
  5636. tx=_("selected"))
  5637. )
  5638. elif curr_sel_obj.kind == 'excellon':
  5639. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5640. color='brown',
  5641. name=str(curr_sel_obj.options['name']),
  5642. tx=_("selected"))
  5643. )
  5644. elif curr_sel_obj.kind == 'cncjob':
  5645. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5646. color='blue',
  5647. name=str(curr_sel_obj.options['name']),
  5648. tx=_("selected"))
  5649. )
  5650. elif curr_sel_obj.kind == 'geometry':
  5651. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5652. color='red',
  5653. name=str(curr_sel_obj.options['name']),
  5654. tx=_("selected"))
  5655. )
  5656. def delete_hover_shape(self):
  5657. self.hover_shapes.clear()
  5658. self.hover_shapes.redraw()
  5659. def draw_hover_shape(self, sel_obj, color=None):
  5660. """
  5661. :param sel_obj: The object for which the hover shape must be drawn
  5662. :param color: The color of the hover shape
  5663. :return: None
  5664. """
  5665. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5666. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5667. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5668. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5669. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5670. if self.defaults['units'].upper() == 'MM':
  5671. hover_rect = hover_rect.buffer(-0.1)
  5672. hover_rect = hover_rect.buffer(0.2)
  5673. else:
  5674. hover_rect = hover_rect.buffer(-0.00393)
  5675. hover_rect = hover_rect.buffer(0.00787)
  5676. # if color:
  5677. # face = Color(color)
  5678. # face.alpha = 0.2
  5679. # outline = Color(color, alpha=0.8)
  5680. # else:
  5681. # face = Color(self.defaults['global_sel_fill'])
  5682. # face.alpha = 0.2
  5683. # outline = self.defaults['global_sel_line']
  5684. if color:
  5685. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5686. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5687. else:
  5688. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5689. outline = self.defaults['global_sel_line']
  5690. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5691. if self.is_legacy is True:
  5692. self.hover_shapes.redraw()
  5693. def delete_selection_shape(self):
  5694. self.move_tool.sel_shapes.clear()
  5695. self.move_tool.sel_shapes.redraw()
  5696. def draw_selection_shape(self, sel_obj, color=None):
  5697. """
  5698. Will draw a selection shape around the selected object.
  5699. :param sel_obj: The object for which the selection shape must be drawn
  5700. :param color: The color for the selection shape.
  5701. :return: None
  5702. """
  5703. if sel_obj is None:
  5704. return
  5705. # it's a line without area
  5706. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5707. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5708. # it's a geometry with area
  5709. else:
  5710. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5711. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5712. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5713. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5714. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5715. b_sel_rect = None
  5716. try:
  5717. if self.defaults['units'].upper() == 'MM':
  5718. b_sel_rect = sel_rect.buffer(-0.1)
  5719. b_sel_rect = b_sel_rect.buffer(0.2)
  5720. else:
  5721. b_sel_rect = sel_rect.buffer(-0.00393)
  5722. b_sel_rect = b_sel_rect.buffer(0.00787)
  5723. except Exception:
  5724. pass
  5725. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5726. b_sel_rect = sel_rect
  5727. if color:
  5728. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5729. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5730. else:
  5731. if self.is_legacy is False:
  5732. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5733. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5734. else:
  5735. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5736. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5737. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5738. color=outline,
  5739. face_color=face,
  5740. update=True,
  5741. layer=0,
  5742. tolerance=None))
  5743. if self.is_legacy is True:
  5744. self.move_tool.sel_shapes.redraw()
  5745. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5746. """
  5747. Will draw a selection shape when dragging mouse on canvas.
  5748. :param old_coords: Old coordinates
  5749. :param coords: New coordinates
  5750. :param kwargs: Keyword arguments
  5751. :return:
  5752. """
  5753. if 'color' in kwargs:
  5754. color = kwargs['color']
  5755. else:
  5756. color = self.defaults['global_sel_line']
  5757. if 'face_color' in kwargs:
  5758. face_color = kwargs['face_color']
  5759. else:
  5760. face_color = self.defaults['global_sel_fill']
  5761. if 'face_alpha' in kwargs:
  5762. face_alpha = kwargs['face_alpha']
  5763. else:
  5764. face_alpha = 0.3
  5765. x0, y0 = old_coords
  5766. x1, y1 = coords
  5767. pt1 = (x0, y0)
  5768. pt2 = (x1, y0)
  5769. pt3 = (x1, y1)
  5770. pt4 = (x0, y1)
  5771. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5772. # color_t = Color(face_color)
  5773. # color_t.alpha = face_alpha
  5774. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5775. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5776. layer=0, tolerance=None)
  5777. if self.is_legacy is True:
  5778. self.move_tool.sel_shapes.redraw()
  5779. def obj_properties(self):
  5780. """
  5781. Will launch the object Properties Tool
  5782. :return:
  5783. """
  5784. self.defaults.report_usage("obj_properties()")
  5785. self.properties_tool.run(toggle=False)
  5786. def on_project_context_save(self):
  5787. """
  5788. Wrapper, will save the object function of it's type
  5789. :return:
  5790. """
  5791. sel_objects = self.collection.get_selected()
  5792. len_objects = len(sel_objects)
  5793. cnt = 0
  5794. if len_objects > 1:
  5795. for o in sel_objects:
  5796. if o.kind == 'cncjob':
  5797. cnt += 1
  5798. if len_objects == cnt:
  5799. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5800. _filter_ = self.defaults['cncjob_save_filters'] + \
  5801. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5802. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5803. try:
  5804. filename, _f = FCFileSaveDialog.get_saved_filename(
  5805. caption=_("Export Code ..."),
  5806. directory=dir_file_to_save,
  5807. ext_filter=_filter_
  5808. )
  5809. except TypeError:
  5810. filename, _f = FCFileSaveDialog.get_saved_filename(
  5811. caption=_("Export Code ..."),
  5812. ext_filter=_filter_)
  5813. filename = filename.rpartition('/')[0]
  5814. for ob in sel_objects:
  5815. ob.read_form()
  5816. fname = '%s/%s' % (filename, ob.options['name'])
  5817. ob.export_gcode_handler(fname, is_gcode=True)
  5818. return
  5819. obj = self.collection.get_active()
  5820. if type(obj) == GeometryObject:
  5821. self.f_handlers.on_file_exportdxf()
  5822. elif type(obj) == ExcellonObject:
  5823. self.f_handlers.on_file_saveexcellon()
  5824. elif type(obj) == CNCJobObject:
  5825. obj.on_exportgcode_button_click()
  5826. elif type(obj) == GerberObject:
  5827. self.f_handlers.on_file_savegerber()
  5828. elif type(obj) == ScriptObject:
  5829. self.f_handlers.on_file_savescript()
  5830. elif type(obj) == DocumentObject:
  5831. self.f_handlers.on_file_savedocument()
  5832. def obj_move(self):
  5833. """
  5834. Callback for the Move menu entry in various Context Menu's.
  5835. :return:
  5836. """
  5837. self.defaults.report_usage("obj_move()")
  5838. self.move_tool.run(toggle=False)
  5839. # ###############################################################################################################
  5840. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5841. # ###############################################################################################################
  5842. def init_code_editor(self, name):
  5843. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5844. # add the tab if it was closed
  5845. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5846. self.text_editor_tab.setObjectName('text_editor_tab')
  5847. # delete the absolute and relative position and messages in the infobar
  5848. # self.ui.position_label.setText("")
  5849. # self.ui.rel_position_label.setText("")
  5850. # hide coordinates toolbars in the infobar while in DB
  5851. self.ui.coords_toolbar.hide()
  5852. self.ui.delta_coords_toolbar.hide()
  5853. self.toggle_codeeditor = True
  5854. self.text_editor_tab.code_editor.completer_enable = False
  5855. self.text_editor_tab.buttonRun.hide()
  5856. # make sure to keep a reference to the code editor
  5857. self.reference_code_editor = self.text_editor_tab.code_editor
  5858. # Switch plot_area to CNCJob tab
  5859. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5860. def on_view_source(self):
  5861. """
  5862. Called when the user wants to see the source file of the selected object
  5863. :return:
  5864. """
  5865. try:
  5866. obj = self.collection.get_active()
  5867. except Exception as e:
  5868. self.log.debug("App.on_view_source() --> %s" % str(e))
  5869. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5870. return 'fail'
  5871. if obj is None:
  5872. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5873. return 'fail'
  5874. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5875. self.proc_container.view.set_busy('%s...' % _("Loading"))
  5876. flt = "All Files (*.*)"
  5877. if obj.kind == 'gerber':
  5878. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5879. elif obj.kind == 'excellon':
  5880. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5881. elif obj.kind == 'cncjob':
  5882. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5883. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5884. # add the tab if it was closed
  5885. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5886. self.source_editor_tab.setObjectName('source_editor_tab')
  5887. # delete the absolute and relative position and messages in the infobar
  5888. # self.ui.position_label.setText("")
  5889. # self.ui.rel_position_label.setText("")
  5890. # hide coordinates toolbars in the infobar while in DB
  5891. self.ui.coords_toolbar.hide()
  5892. self.ui.delta_coords_toolbar.hide()
  5893. self.source_editor_tab.code_editor.completer_enable = False
  5894. self.source_editor_tab.buttonRun.hide()
  5895. # Switch plot_area to CNCJob tab
  5896. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5897. try:
  5898. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5899. except TypeError:
  5900. pass
  5901. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5902. try:
  5903. self.source_editor_tab.buttonSave.clicked.disconnect()
  5904. except TypeError:
  5905. pass
  5906. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5907. # then append the text from GCode to the text editor
  5908. if obj.kind == 'cncjob':
  5909. try:
  5910. file = obj.export_gcode(to_file=True)
  5911. if file == 'fail':
  5912. return 'fail'
  5913. except AttributeError:
  5914. self.inform.emit('[WARNING_NOTCL] %s' %
  5915. _("There is no selected object for which to see it's source file code."))
  5916. return 'fail'
  5917. else:
  5918. try:
  5919. file = StringIO(obj.source_file)
  5920. except (AttributeError, TypeError):
  5921. self.inform.emit('[WARNING_NOTCL] %s' %
  5922. _("There is no selected object for which to see it's source file code."))
  5923. return 'fail'
  5924. self.source_editor_tab.t_frame.hide()
  5925. try:
  5926. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5927. except Exception as e:
  5928. self.log.debug('App.on_view_source() -->%s' % str(e))
  5929. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5930. return
  5931. self.source_editor_tab.t_frame.show()
  5932. self.proc_container.view.set_idle()
  5933. # self.ui.show()
  5934. def on_toggle_code_editor(self):
  5935. self.defaults.report_usage("on_toggle_code_editor()")
  5936. if self.toggle_codeeditor is False:
  5937. self.init_code_editor(name=_("Code Editor"))
  5938. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5939. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5940. self.text_editor_tab.buttonSave.clicked.disconnect()
  5941. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5942. else:
  5943. for idx in range(self.ui.plot_tab_area.count()):
  5944. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5945. self.ui.plot_tab_area.closeTab(idx)
  5946. break
  5947. self.toggle_codeeditor = False
  5948. def on_code_editor_close(self):
  5949. self.toggle_codeeditor = False
  5950. def goto_text_line(self):
  5951. """
  5952. Will scroll a text to the specified text line.
  5953. :return: None
  5954. """
  5955. dia_box = Dialog_box(title=_("Go to Line ..."),
  5956. label='%s:' % _("Line"),
  5957. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5958. initial_text='')
  5959. try:
  5960. line = int(dia_box.location) - 1
  5961. except (ValueError, TypeError):
  5962. line = 0
  5963. if dia_box.ok:
  5964. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5965. # at the top of the window
  5966. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5967. # get the document() of the AppTextEditor
  5968. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5969. # create a Text Cursor based on the searched line
  5970. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5971. # set cursor of the code editor with the cursor at the searcehd line
  5972. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5973. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5974. """
  5975. Re-generates all plots from all objects.
  5976. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5977. :param muted: if True don't print messages
  5978. :param use_thread: if True will use threading for plotting the objects
  5979. :return: None
  5980. """
  5981. self.log.debug("Plot_all()")
  5982. if muted is not True:
  5983. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5984. for plot_obj in self.collection.get_list():
  5985. def worker_task(obj):
  5986. with self.proc_container.new("Plotting"):
  5987. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5988. if fit_view is True:
  5989. self.app_obj.object_plotted.emit(obj)
  5990. if use_thread is True:
  5991. # Send to worker
  5992. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5993. else:
  5994. worker_task(plot_obj)
  5995. def register_folder(self, filename):
  5996. """
  5997. Register the last folder used by the app to open something
  5998. :param filename: the last folder is extracted from the filename
  5999. :return: None
  6000. """
  6001. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6002. def register_save_folder(self, filename):
  6003. """
  6004. Register the last folder used by the app to save something
  6005. :param filename: the last folder is extracted from the filename
  6006. :return: None
  6007. """
  6008. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6009. # def set_progress_bar(self, percentage, text=""):
  6010. # """
  6011. # Set a progress bar to a value (percentage)
  6012. #
  6013. # :param percentage: Value set to the progressbar
  6014. # :param text: Not used
  6015. # :return: None
  6016. # """
  6017. # self.ui.progress_bar.setValue(int(percentage))
  6018. def setup_recent_items(self):
  6019. """
  6020. Setup a dictionary with the recent files accessed, organized by type
  6021. :return:
  6022. """
  6023. icons = {
  6024. "gerber": self.resource_location + "/flatcam_icon16.png",
  6025. "excellon": self.resource_location + "/drill16.png",
  6026. 'geometry': self.resource_location + "/geometry16.png",
  6027. "cncjob": self.resource_location + "/cnc16.png",
  6028. "script": self.resource_location + "/script_new24.png",
  6029. "document": self.resource_location + "/notes16_1.png",
  6030. "project": self.resource_location + "/project16.png",
  6031. "svg": self.resource_location + "/geometry16.png",
  6032. "dxf": self.resource_location + "/dxf16.png",
  6033. "pdf": self.resource_location + "/pdf32.png",
  6034. "image": self.resource_location + "/image16.png"
  6035. }
  6036. try:
  6037. image_opener = self.image_tool.import_image
  6038. except AttributeError:
  6039. image_opener = None
  6040. openers = {
  6041. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  6042. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  6043. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  6044. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  6045. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  6046. "document": None,
  6047. 'project': self.f_handlers.open_project,
  6048. 'svg': self.f_handlers.import_svg,
  6049. 'dxf': self.f_handlers.import_dxf,
  6050. 'image': image_opener,
  6051. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6052. }
  6053. # Open recent file for files
  6054. try:
  6055. f = open(self.data_path + '/recent.json')
  6056. except IOError:
  6057. App.log.error("Failed to load recent item list.")
  6058. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  6059. return
  6060. try:
  6061. self.recent = json.load(f)
  6062. except json.errors.JSONDecodeError:
  6063. App.log.error("Failed to parse recent item list.")
  6064. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  6065. f.close()
  6066. return
  6067. f.close()
  6068. # Open recent file for projects
  6069. try:
  6070. fp = open(self.data_path + '/recent_projects.json')
  6071. except IOError:
  6072. App.log.error("Failed to load recent project item list.")
  6073. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  6074. return
  6075. try:
  6076. self.recent_projects = json.load(fp)
  6077. except json.errors.JSONDecodeError:
  6078. App.log.error("Failed to parse recent project item list.")
  6079. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  6080. fp.close()
  6081. return
  6082. fp.close()
  6083. # Closure needed to create callbacks in a loop.
  6084. # Otherwise late binding occurs.
  6085. def make_callback(func, fname):
  6086. def opener():
  6087. func(fname)
  6088. return opener
  6089. def reset_recent_files():
  6090. # Reset menu
  6091. self.ui.recent.clear()
  6092. self.recent = []
  6093. try:
  6094. ff = open(self.data_path + '/recent.json', 'w')
  6095. except IOError:
  6096. App.log.error("Failed to open recent items file for writing.")
  6097. return
  6098. json.dump(self.recent, ff)
  6099. def reset_recent_projects():
  6100. # Reset menu
  6101. self.ui.recent_projects.clear()
  6102. self.recent_projects = []
  6103. try:
  6104. frp = open(self.data_path + '/recent_projects.json', 'w')
  6105. except IOError:
  6106. App.log.error("Failed to open recent projects items file for writing.")
  6107. return
  6108. json.dump(self.recent, frp)
  6109. # Reset menu
  6110. self.ui.recent.clear()
  6111. self.ui.recent_projects.clear()
  6112. # Create menu items for projects
  6113. for recent in self.recent_projects:
  6114. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6115. if recent['kind'] == 'project':
  6116. try:
  6117. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6118. # Attach callback
  6119. o = make_callback(openers[recent["kind"]], recent['filename'])
  6120. action.triggered.connect(o)
  6121. self.ui.recent_projects.addAction(action)
  6122. except KeyError:
  6123. App.log.error("Unsupported file type: %s" % recent["kind"])
  6124. # Last action in Recent Files menu is one that Clear the content
  6125. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6126. (_("Clear Recent projects")), self)
  6127. clear_action_proj.triggered.connect(reset_recent_projects)
  6128. self.ui.recent_projects.addSeparator()
  6129. self.ui.recent_projects.addAction(clear_action_proj)
  6130. # Create menu items for files
  6131. for recent in self.recent:
  6132. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6133. if recent['kind'] != 'project':
  6134. try:
  6135. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6136. # Attach callback
  6137. o = make_callback(openers[recent["kind"]], recent['filename'])
  6138. action.triggered.connect(o)
  6139. self.ui.recent.addAction(action)
  6140. except KeyError:
  6141. App.log.error("Unsupported file type: %s" % recent["kind"])
  6142. # Last action in Recent Files menu is one that Clear the content
  6143. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  6144. (_("Clear Recent files")), self)
  6145. clear_action.triggered.connect(reset_recent_files)
  6146. self.ui.recent.addSeparator()
  6147. self.ui.recent.addAction(clear_action)
  6148. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6149. # self.ui.menufilerecent.set_submenu(recent_menu)
  6150. # recent_menu.show_all()
  6151. # self.ui.recent.show()
  6152. self.log.debug("Recent items list has been populated.")
  6153. def on_properties_tab_click(self, index):
  6154. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  6155. self.setup_default_properties_tab()
  6156. def setup_default_properties_tab(self):
  6157. """
  6158. Default text for the Properties tab when is not taken by the Object UI.
  6159. :return:
  6160. """
  6161. # label = QtWidgets.QLabel("Choose an item from Project")
  6162. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6163. # sel_title = QtWidgets.QTextEdit()
  6164. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6165. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6166. #
  6167. # f_settings = QSettings("Open Source", "FlatCAM")
  6168. # if f_settings.contains("notebook_font_size"):
  6169. # fsize = f_settings.value('notebook_font_size', type=int)
  6170. # else:
  6171. # fsize = 12
  6172. #
  6173. # tsize = fsize + int(fsize / 2)
  6174. #
  6175. # selected_text = ''
  6176. #
  6177. # sel_title.setText(selected_text)
  6178. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6179. # Tree Widget
  6180. d_properties_tw = FCTree(columns=2)
  6181. d_properties_tw.setObjectName("default_properties")
  6182. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6183. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6184. root = d_properties_tw.invisibleRootItem()
  6185. font = QtGui.QFont()
  6186. font.setBold(True)
  6187. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6188. # main Items categories
  6189. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6190. d_properties_tw.addChild(parent=general_cat,
  6191. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6192. d_properties_tw.addChild(parent=general_cat,
  6193. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6194. d_properties_tw.addChild(parent=general_cat,
  6195. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6196. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6197. d_properties_tw.addChild(parent=grid_cat,
  6198. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6199. column1=True)
  6200. d_properties_tw.addChild(parent=grid_cat,
  6201. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6202. column1=True)
  6203. d_properties_tw.addChild(parent=grid_cat,
  6204. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6205. column1=True)
  6206. d_properties_tw.addChild(parent=grid_cat,
  6207. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6208. column1=True)
  6209. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6210. d_properties_tw.addChild(parent=canvas_cat,
  6211. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6212. column1=True)
  6213. d_properties_tw.addChild(parent=canvas_cat,
  6214. title=['%s:' % _("Workspace active"),
  6215. '%s' % str(self.defaults['global_workspace'])],
  6216. column1=True)
  6217. d_properties_tw.addChild(parent=canvas_cat,
  6218. title=['%s:' % _("Workspace size"),
  6219. '%s' % str(self.defaults['global_workspaceT'])],
  6220. column1=True)
  6221. d_properties_tw.addChild(parent=canvas_cat,
  6222. title=['%s:' % _("Workspace orientation"),
  6223. '%s' % _("Portrait") if self.defaults[
  6224. 'global_workspace_orientation'] == 'p' else
  6225. _("Landscape")],
  6226. column1=True)
  6227. d_properties_tw.addChild(parent=canvas_cat,
  6228. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6229. column1=True)
  6230. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6231. def setup_obj_classes(self):
  6232. """
  6233. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6234. class.
  6235. :return: None
  6236. """
  6237. FlatCAMObj.app = self
  6238. ObjectCollection.app = self
  6239. Gerber.app = self
  6240. Excellon.app = self
  6241. Geometry.app = self
  6242. CNCjob.app = self
  6243. FCProcess.app = self
  6244. FCProcessContainer.app = self
  6245. OptionsGroupUI.app = self
  6246. def version_check(self):
  6247. """
  6248. Checks for the latest version of the program. Alerts the
  6249. user if theirs is outdated. This method is meant to be run
  6250. in a separate thread.
  6251. :return: None
  6252. """
  6253. self.log.debug("version_check()")
  6254. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6255. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6256. App.version_url,
  6257. str(self.defaults['global_serial']),
  6258. str(self.version),
  6259. str(self.os),
  6260. urllib.parse.urlencode(self.defaults["global_stats"])
  6261. )
  6262. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6263. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6264. # urllib.parse.urlencode(self.defaults["global_stats"])
  6265. else:
  6266. # no_stats dict; just so it won't break things on website
  6267. no_ststs_dict = {"global_ststs": {}}
  6268. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6269. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6270. self.log.debug("Checking for updates @ %s" % full_url)
  6271. # ## Get the data
  6272. try:
  6273. f = urllib.request.urlopen(full_url)
  6274. except Exception:
  6275. # App.log.warning("Failed checking for latest version. Could not connect.")
  6276. self.log.warning("Failed checking for latest version. Could not connect.")
  6277. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6278. return
  6279. try:
  6280. data = json.load(f)
  6281. except Exception as e:
  6282. App.log.error("Could not parse information about latest version.")
  6283. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6284. self.log.debug("json.load(): %s" % str(e))
  6285. f.close()
  6286. return
  6287. f.close()
  6288. # ## Latest version?
  6289. if self.version >= data["version"]:
  6290. self.log.debug("FlatCAM is up to date!")
  6291. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6292. return
  6293. self.log.debug("Newer version available.")
  6294. self.message.emit(
  6295. _("Newer Version Available"),
  6296. '%s<br><br>><b>%s</b><br>%s' % (
  6297. _("There is a newer version of FlatCAM available for download:"),
  6298. str(data["name"]),
  6299. str(data["message"])
  6300. ),
  6301. _("info")
  6302. )
  6303. def on_plotcanvas_setup(self, container=None):
  6304. """
  6305. This is doing the setup for the plot area (canvas).
  6306. :param container: QT Widget where to install the canvas
  6307. :return: None
  6308. """
  6309. if container:
  6310. plot_container = container
  6311. else:
  6312. plot_container = self.ui.right_layout
  6313. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6314. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6315. self.is_legacy = True
  6316. self.defaults["global_graphic_engine"] = "2D"
  6317. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6318. else:
  6319. try:
  6320. self.plotcanvas = PlotCanvas(plot_container, self)
  6321. except Exception as er:
  6322. msg_txt = traceback.format_exc()
  6323. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6324. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6325. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6326. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6327. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6328. msg += msg_txt
  6329. self.inform.emit(msg)
  6330. return 'fail'
  6331. # So it can receive key presses
  6332. self.plotcanvas.native.setFocus()
  6333. if self.is_legacy is False:
  6334. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6335. # Set the mouse button for panning
  6336. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6337. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6338. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6339. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6340. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6341. # Keys over plot enabled
  6342. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6343. if self.defaults['global_cursor_type'] == 'small':
  6344. self.app_cursor = self.plotcanvas.new_cursor()
  6345. else:
  6346. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6347. if self.ui.grid_snap_btn.isChecked():
  6348. self.app_cursor.enabled = True
  6349. else:
  6350. self.app_cursor.enabled = False
  6351. if self.is_legacy is False:
  6352. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6353. else:
  6354. # will use the default Matplotlib axes
  6355. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6356. def on_zoom_fit(self):
  6357. """
  6358. Callback for zoom-fit request. This can be either from the corresponding
  6359. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6360. with axes limits from the geometry bounds of all objects.
  6361. :return: None
  6362. """
  6363. if self.is_legacy is False:
  6364. self.plotcanvas.fit_view()
  6365. else:
  6366. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6367. width = xmax - xmin
  6368. height = ymax - ymin
  6369. xmin -= 0.05 * width
  6370. xmax += 0.05 * width
  6371. ymin -= 0.05 * height
  6372. ymax += 0.05 * height
  6373. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6374. def on_zoom_in(self):
  6375. """
  6376. Callback for zoom-in request.
  6377. :return:
  6378. """
  6379. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6380. def on_zoom_out(self):
  6381. """
  6382. Callback for zoom-out request.
  6383. :return:
  6384. """
  6385. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6386. def disable_all_plots(self):
  6387. self.defaults.report_usage("disable_all_plots()")
  6388. self.disable_plots(self.collection.get_list())
  6389. self.inform.emit('[success] %s' % _("All plots disabled."))
  6390. def disable_other_plots(self):
  6391. self.defaults.report_usage("disable_other_plots()")
  6392. self.disable_plots(self.collection.get_non_selected())
  6393. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6394. def enable_all_plots(self):
  6395. self.defaults.report_usage("enable_all_plots()")
  6396. self.enable_plots(self.collection.get_list())
  6397. self.inform.emit('[success] %s' % _("All plots enabled."))
  6398. def enable_other_plots(self):
  6399. self.defaults.report_usage("enable_other_plots()")
  6400. self.enable_plots(self.collection.get_non_selected())
  6401. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6402. def on_enable_sel_plots(self):
  6403. self.log.debug("App.on_enable_sel_plot()")
  6404. object_list = self.collection.get_selected()
  6405. self.enable_plots(objects=object_list)
  6406. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6407. def on_disable_sel_plots(self):
  6408. self.log.debug("App.on_disable_sel_plot()")
  6409. # self.inform.emit(_("Disabling plots ..."))
  6410. object_list = self.collection.get_selected()
  6411. self.disable_plots(objects=object_list)
  6412. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6413. def enable_plots(self, objects):
  6414. """
  6415. Enable plots
  6416. :param objects: list of Objects to be enabled
  6417. :return:
  6418. """
  6419. self.log.debug("Enabling plots ...")
  6420. # self.inform.emit(_("Working ..."))
  6421. for obj in objects:
  6422. if obj.options['plot'] is False:
  6423. obj.options.set_change_callback(lambda x: None)
  6424. obj.options['plot'] = True
  6425. try:
  6426. # only the Gerber obj has on_plot_cb_click() method
  6427. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6428. # disable this cb while disconnected,
  6429. # in case the operation takes time the user is not allowed to change it
  6430. obj.ui.plot_cb.setDisabled(True)
  6431. except AttributeError:
  6432. pass
  6433. obj.set_form_item("plot")
  6434. try:
  6435. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6436. obj.ui.plot_cb.setDisabled(False)
  6437. except AttributeError:
  6438. pass
  6439. obj.options.set_change_callback(obj.on_options_change)
  6440. self.collection.update_view()
  6441. def worker_task(objs):
  6442. with self.proc_container.new(_("Enabling plots ...")):
  6443. for plot_obj in objs:
  6444. # obj.options['plot'] = True
  6445. if isinstance(plot_obj, CNCJobObject):
  6446. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6447. else:
  6448. plot_obj.plot(visible=True)
  6449. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6450. def disable_plots(self, objects):
  6451. """
  6452. Disables plots
  6453. :param objects: list of Objects to be disabled
  6454. :return:
  6455. """
  6456. self.log.debug("Disabling plots ...")
  6457. # self.inform.emit(_("Working ..."))
  6458. for obj in objects:
  6459. if obj.options['plot'] is True:
  6460. obj.options.set_change_callback(lambda x: None)
  6461. obj.options['plot'] = False
  6462. try:
  6463. # only the Gerber obj has on_plot_cb_click() method
  6464. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6465. obj.ui.plot_cb.setDisabled(True)
  6466. except AttributeError:
  6467. pass
  6468. obj.set_form_item("plot")
  6469. try:
  6470. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6471. obj.ui.plot_cb.setDisabled(False)
  6472. except AttributeError:
  6473. pass
  6474. obj.options.set_change_callback(obj.on_options_change)
  6475. try:
  6476. self.delete_selection_shape()
  6477. except Exception as e:
  6478. self.log.debug("App.disable_plots() --> %s" % str(e))
  6479. self.collection.update_view()
  6480. def worker_task(objs):
  6481. with self.proc_container.new(_("Disabling plots ...")):
  6482. for plot_obj in objs:
  6483. # obj.options['plot'] = True
  6484. if isinstance(plot_obj, CNCJobObject):
  6485. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6486. else:
  6487. plot_obj.plot(visible=False)
  6488. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6489. def toggle_plots(self, objects):
  6490. """
  6491. Toggle plots visibility
  6492. :param objects: list of Objects for which to be toggled the visibility
  6493. :return: None
  6494. """
  6495. # if no objects selected then do nothing
  6496. if not self.collection.get_selected():
  6497. return
  6498. self.log.debug("Toggling plots ...")
  6499. self.inform.emit(_("Working ..."))
  6500. for obj in objects:
  6501. if obj.options['plot'] is False:
  6502. obj.options['plot'] = True
  6503. else:
  6504. obj.options['plot'] = False
  6505. self.app_obj.plots_updated.emit()
  6506. def clear_plots(self):
  6507. """
  6508. Clear the plots
  6509. :return: None
  6510. """
  6511. objects = self.collection.get_list()
  6512. for obj in objects:
  6513. obj.clear(obj == objects[-1])
  6514. # Clear pool to free memory
  6515. self.clear_pool()
  6516. def on_set_color_action_triggered(self):
  6517. """
  6518. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6519. :return:
  6520. """
  6521. new_color = self.defaults['gerber_plot_fill']
  6522. clicked_action = self.sender()
  6523. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6524. act_name = clicked_action.text()
  6525. sel_obj_list = self.collection.get_selected()
  6526. if not sel_obj_list:
  6527. return
  6528. # a default value, I just chose this one
  6529. alpha_level = 'BF'
  6530. for sel_obj in sel_obj_list:
  6531. if sel_obj.kind == 'excellon':
  6532. alpha_level = str(hex(
  6533. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6534. elif sel_obj.kind == 'gerber':
  6535. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6536. elif sel_obj.kind == 'geometry':
  6537. alpha_level = 'FF'
  6538. else:
  6539. self.log.debug(
  6540. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6541. continue
  6542. sel_obj.alpha_level = alpha_level
  6543. if act_name == _('Red'):
  6544. new_color = '#FF0000' + alpha_level
  6545. if act_name == _('Blue'):
  6546. new_color = '#0000FF' + alpha_level
  6547. if act_name == _('Yellow'):
  6548. new_color = '#FFDF00' + alpha_level
  6549. if act_name == _('Green'):
  6550. new_color = '#00FF00' + alpha_level
  6551. if act_name == _('Purple'):
  6552. new_color = '#FF00FF' + alpha_level
  6553. if act_name == _('Brown'):
  6554. new_color = '#A52A2A' + alpha_level
  6555. if act_name == _('White'):
  6556. new_color = '#FFFFFF' + alpha_level
  6557. if act_name == _('Black'):
  6558. new_color = '#000000' + alpha_level
  6559. if act_name == _('Custom'):
  6560. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6561. c_dialog = QtWidgets.QColorDialog()
  6562. plot_fill_color = c_dialog.getColor(initial=new_color)
  6563. if plot_fill_color.isValid() is False:
  6564. return
  6565. new_color = str(plot_fill_color.name()) + alpha_level
  6566. if act_name == _("Default"):
  6567. for sel_obj in sel_obj_list:
  6568. if sel_obj.kind == 'excellon':
  6569. new_color = self.defaults['excellon_plot_fill']
  6570. new_line_color = self.defaults['excellon_plot_line']
  6571. elif sel_obj.kind == 'gerber':
  6572. new_color = self.defaults['gerber_plot_fill']
  6573. new_line_color = self.defaults['gerber_plot_line']
  6574. elif sel_obj.kind == 'geometry':
  6575. new_color = self.defaults['geometry_plot_line']
  6576. new_line_color = self.defaults['geometry_plot_line']
  6577. else:
  6578. self.log.debug(
  6579. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6580. continue
  6581. sel_obj.fill_color = new_color
  6582. sel_obj.outline_color = new_line_color
  6583. sel_obj.shapes.redraw(
  6584. update_colors=(new_color, new_line_color)
  6585. )
  6586. return
  6587. if act_name == _("Opacity"):
  6588. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6589. # '%s:' % _("Value"),
  6590. # min=0, max=255, step=1, value=191)
  6591. alpha_dialog = FCInputDialogSlider(
  6592. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6593. alpha_level, ok_button = alpha_dialog.get_results()
  6594. if ok_button:
  6595. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6596. for sel_obj in sel_obj_list:
  6597. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6598. sel_obj.shapes.redraw(
  6599. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6600. )
  6601. return
  6602. new_line_color = color_variant(new_color[:7], 0.7)
  6603. if act_name == _("White"):
  6604. new_line_color = color_variant("#dedede", 0.7)
  6605. for sel_obj in sel_obj_list:
  6606. sel_obj.fill_color = new_color
  6607. sel_obj.outline_color = new_line_color
  6608. sel_obj.shapes.redraw(
  6609. update_colors=(new_color, new_line_color)
  6610. )
  6611. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6612. group = self.collection.group_items["gerber"]
  6613. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6614. new_c = (new_line_color, new_color)
  6615. for sel_obj in sel_obj_list:
  6616. if sel_obj.kind == 'gerber':
  6617. item = sel_obj.item
  6618. item_index = self.collection.index(item.row(), 0, group_index)
  6619. idx = item_index.row()
  6620. self.defaults["gerber_color_list"][idx] = new_c
  6621. def generate_cnc_job(self, objects):
  6622. """
  6623. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6624. :param objects: Selected objects in the Project Tab
  6625. :return:
  6626. """
  6627. self.defaults.report_usage("generate_cnc_job()")
  6628. # for obj in objects:
  6629. # obj.generatecncjob()
  6630. for obj in objects:
  6631. obj.on_generatecnc_button_click()
  6632. def start_delayed_quit(self, delay, filename, should_quit=None):
  6633. """
  6634. :param delay: period of checking if project file size is more than zero; in seconds
  6635. :param filename: the name of the project file to be checked periodically for size more than zero
  6636. :param should_quit: if the task finished will be followed by an app quit; boolean
  6637. :return:
  6638. """
  6639. to_quit = should_quit
  6640. self.save_timer = QtCore.QTimer()
  6641. self.save_timer.setInterval(delay)
  6642. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6643. self.save_timer.start()
  6644. def check_project_file_size(self, filename, should_quit=None):
  6645. """
  6646. :param filename: the name of the project file to be checked periodically for size more than zero
  6647. :param should_quit: will quit the app if True; boolean
  6648. :return:
  6649. """
  6650. try:
  6651. if os.stat(filename).st_size > 0:
  6652. self.save_in_progress = False
  6653. self.save_timer.stop()
  6654. if should_quit:
  6655. self.app_quit.emit()
  6656. except Exception:
  6657. traceback.print_exc()
  6658. def save_project_auto(self):
  6659. """
  6660. Called periodically to save the project.
  6661. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6662. # progress.
  6663. :return:
  6664. """
  6665. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6666. self.on_file_saveproject()
  6667. def save_project_auto_update(self):
  6668. """
  6669. Update the auto save time interval value.
  6670. :return:
  6671. """
  6672. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6673. try:
  6674. if self.autosave_timer.isActive():
  6675. self.autosave_timer.stop()
  6676. except Exception:
  6677. pass
  6678. if self.defaults['global_autosave'] is True:
  6679. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6680. self.autosave_timer.start()
  6681. def on_options_app2project(self):
  6682. """
  6683. Callback for Options->Transfer Options->App=>Project. Copies options
  6684. from application defaults to project defaults.
  6685. :return: None
  6686. """
  6687. self.defaults.report_usage("on_options_app2project")
  6688. self.preferencesUiManager.defaults_read_form()
  6689. self.options.update(self.defaults)
  6690. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6691. """
  6692. Shows a message on the FlatCAM Shell
  6693. :param new_line:
  6694. :param msg: Message to display.
  6695. :param show: Opens the shell.
  6696. :param error: Shows the message as an error.
  6697. :param warning: Shows the message as an warning.
  6698. :param success: Shows the message as an success.
  6699. :param selected: Indicate that something was selected on canvas
  6700. :return: None
  6701. """
  6702. end = '\n' if new_line is True else ''
  6703. if show:
  6704. self.ui.shell_dock.show()
  6705. try:
  6706. if error:
  6707. self.shell.append_error(msg + end)
  6708. elif warning:
  6709. self.shell.append_warning(msg + end)
  6710. elif success:
  6711. self.shell.append_success(msg + end)
  6712. elif selected:
  6713. self.shell.append_selected(msg + end)
  6714. else:
  6715. self.shell.append_output(msg + end)
  6716. except AttributeError:
  6717. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6718. def dec_format(self, val, dec=None):
  6719. """
  6720. Returns a formatted float value with a certain number of decimals
  6721. """
  6722. dec_nr = dec if dec is not None else self.decimals
  6723. return float('%.*f' % (dec_nr, val))
  6724. class ArgsThread(QtCore.QObject):
  6725. open_signal = pyqtSignal(list)
  6726. start = pyqtSignal()
  6727. stop = pyqtSignal()
  6728. if sys.platform == 'win32':
  6729. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6730. else:
  6731. address = ('/tmp/testipc', 'AF_UNIX')
  6732. def __init__(self):
  6733. super().__init__()
  6734. self.listener = None
  6735. self.thread_exit = False
  6736. self.start.connect(self.run)
  6737. self.stop.connect(self.close_listener)
  6738. def my_loop(self, address):
  6739. try:
  6740. self.listener = Listener(*address)
  6741. while self.thread_exit is False:
  6742. conn = self.listener.accept()
  6743. self.serve(conn)
  6744. except socket.error:
  6745. try:
  6746. conn = Client(*address)
  6747. conn.send(sys.argv)
  6748. conn.send('close')
  6749. # close the current instance only if there are args
  6750. if len(sys.argv) > 1:
  6751. try:
  6752. self.listener.close()
  6753. except Exception:
  6754. pass
  6755. sys.exit()
  6756. except ConnectionRefusedError:
  6757. if sys.platform == 'win32':
  6758. pass
  6759. else:
  6760. os.system('rm /tmp/testipc')
  6761. self.listener = Listener(*address)
  6762. while True:
  6763. conn = self.listener.accept()
  6764. self.serve(conn)
  6765. def serve(self, conn):
  6766. while self.thread_exit is False:
  6767. msg = conn.recv()
  6768. if msg == 'close':
  6769. break
  6770. self.open_signal.emit(msg)
  6771. conn.close()
  6772. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6773. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6774. @pyqtSlot()
  6775. def run(self):
  6776. self.my_loop(self.address)
  6777. @pyqtSlot()
  6778. def close_listener(self):
  6779. self.thread_exit = True
  6780. self.listener.close()
  6781. class MenuFileHandlers(QtCore.QObject):
  6782. def __init__(self, app):
  6783. super().__init__()
  6784. self.app = app
  6785. self.inform = self.app.inform
  6786. self.splash = self.app.splash
  6787. self.worker_task = self.app.worker_task
  6788. self.defaults = self.app.defaults
  6789. self.pagesize = {}
  6790. def on_fileopengerber(self, signal, name=None):
  6791. """
  6792. File menu callback for opening a Gerber.
  6793. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6794. :param name:
  6795. :return: None
  6796. """
  6797. self.app.log.debug("on_fileopengerber()")
  6798. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6799. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6800. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6801. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6802. "*.outline);;" \
  6803. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6804. "*.mil);;" \
  6805. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6806. "Allegro Files (*.art);;" \
  6807. "Mentor Files (*.pho *.gdo);;" \
  6808. "All Files (*.*)"
  6809. if name is None:
  6810. try:
  6811. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6812. directory=self.app.get_last_folder(),
  6813. filter=_filter_,
  6814. initialFilter=self.app.last_op_gerber_filter)
  6815. except TypeError:
  6816. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6817. filenames = [str(filename) for filename in filenames]
  6818. self.app.last_op_gerber_filter = _f
  6819. else:
  6820. filenames = [name]
  6821. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6822. "Canvas initialization finished in"),
  6823. '%.2f' % self.app.used_time,
  6824. _("Opening Gerber file.")),
  6825. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6826. color=QtGui.QColor("gray"))
  6827. if len(filenames) == 0:
  6828. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6829. else:
  6830. for filename in filenames:
  6831. if filename != '':
  6832. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6833. def on_fileopenexcellon(self, signal, name=None):
  6834. """
  6835. File menu callback for opening an Excellon file.
  6836. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6837. :param name:
  6838. :return: None
  6839. """
  6840. self.app.log.debug("on_fileopenexcellon()")
  6841. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6842. "All Files (*.*)"
  6843. if name is None:
  6844. try:
  6845. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6846. directory=self.app.get_last_folder(),
  6847. filter=_filter_,
  6848. initialFilter=self.app.last_op_excellon_filter)
  6849. except TypeError:
  6850. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6851. filenames = [str(filename) for filename in filenames]
  6852. self.app.last_op_excellon_filter = _f
  6853. else:
  6854. filenames = [str(name)]
  6855. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6856. "Canvas initialization finished in"),
  6857. '%.2f' % self.app.used_time,
  6858. _("Opening Excellon file.")),
  6859. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6860. color=QtGui.QColor("gray"))
  6861. if len(filenames) == 0:
  6862. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6863. else:
  6864. for filename in filenames:
  6865. if filename != '':
  6866. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6867. def on_fileopengcode(self, signal, name=None):
  6868. """
  6869. File menu call back for opening gcode.
  6870. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6871. :param name:
  6872. :return:
  6873. """
  6874. self.app.log.debug("on_fileopengcode()")
  6875. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6876. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6877. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6878. "All Files (*.*)"
  6879. if name is None:
  6880. try:
  6881. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6882. directory=self.app.get_last_folder(),
  6883. filter=_filter_,
  6884. initialFilter=self.app.last_op_gcode_filter)
  6885. except TypeError:
  6886. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6887. filenames = [str(filename) for filename in filenames]
  6888. self.app.last_op_gcode_filter = _f
  6889. else:
  6890. filenames = [name]
  6891. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6892. "Canvas initialization finished in"),
  6893. '%.2f' % self.app.used_time,
  6894. _("Opening G-Code file.")),
  6895. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6896. color=QtGui.QColor("gray"))
  6897. if len(filenames) == 0:
  6898. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6899. else:
  6900. for filename in filenames:
  6901. if filename != '':
  6902. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6903. def on_file_openproject(self, signal):
  6904. """
  6905. File menu callback for opening a project.
  6906. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6907. :return: None
  6908. """
  6909. self.app.log.debug("on_file_openproject()")
  6910. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6911. try:
  6912. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6913. directory=self.app.get_last_folder(), filter=_filter_)
  6914. except TypeError:
  6915. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6916. filename = str(filename)
  6917. if filename == "":
  6918. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6919. else:
  6920. # self.worker_task.emit({'fcn': self.open_project,
  6921. # 'params': [filename]})
  6922. # The above was failing because open_project() is not
  6923. # thread safe. The new_project()
  6924. self.open_project(filename)
  6925. def on_fileopenhpgl2(self, signal, name=None):
  6926. """
  6927. File menu callback for opening a HPGL2.
  6928. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6929. :param name:
  6930. :return: None
  6931. """
  6932. self.app.log.debug("on_fileopenhpgl2()")
  6933. _filter_ = "HPGL2 Files (*.plt);;" \
  6934. "All Files (*.*)"
  6935. if name is None:
  6936. try:
  6937. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6938. directory=self.app.get_last_folder(),
  6939. filter=_filter_)
  6940. except TypeError:
  6941. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6942. filenames = [str(filename) for filename in filenames]
  6943. else:
  6944. filenames = [name]
  6945. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6946. "Canvas initialization finished in"),
  6947. '%.2f' % self.app.used_time,
  6948. _("Opening HPGL2 file.")),
  6949. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6950. color=QtGui.QColor("gray"))
  6951. if len(filenames) == 0:
  6952. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6953. else:
  6954. for filename in filenames:
  6955. if filename != '':
  6956. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6957. def on_file_openconfig(self, signal):
  6958. """
  6959. File menu callback for opening a config file.
  6960. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6961. :return: None
  6962. """
  6963. self.app.log.debug("on_file_openconfig()")
  6964. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6965. try:
  6966. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6967. directory=self.app.data_path, filter=_filter_)
  6968. except TypeError:
  6969. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6970. filter=_filter_)
  6971. if filename == "":
  6972. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6973. else:
  6974. self.open_config_file(filename)
  6975. def on_file_exportsvg(self):
  6976. """
  6977. Callback for menu item File->Export SVG.
  6978. :return: None
  6979. """
  6980. self.app.log.debug("on_file_exportsvg()")
  6981. obj = self.app.collection.get_active()
  6982. if obj is None:
  6983. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  6984. msg = _("Please Select a Geometry object to export")
  6985. msgbox = QtWidgets.QMessageBox()
  6986. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6987. msgbox.setInformativeText(msg)
  6988. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6989. msgbox.setDefaultButton(bt_ok)
  6990. msgbox.exec_()
  6991. return
  6992. # Check for more compatible types and add as required
  6993. if (not isinstance(obj, GeometryObject)
  6994. and not isinstance(obj, GerberObject)
  6995. and not isinstance(obj, CNCJobObject)
  6996. and not isinstance(obj, ExcellonObject)):
  6997. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6998. msgbox = QtWidgets.QMessageBox()
  6999. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7000. msgbox.setInformativeText(msg)
  7001. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7002. msgbox.setDefaultButton(bt_ok)
  7003. msgbox.exec_()
  7004. return
  7005. name = obj.options["name"]
  7006. _filter = "SVG File (*.svg);;All Files (*.*)"
  7007. try:
  7008. filename, _f = FCFileSaveDialog.get_saved_filename(
  7009. caption=_("Export SVG"),
  7010. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  7011. ext_filter=_filter)
  7012. except TypeError:
  7013. filename, _f = FCFileSaveDialog.get_saved_filename(
  7014. caption=_("Export SVG"),
  7015. ext_filter=_filter)
  7016. filename = str(filename)
  7017. if filename == "":
  7018. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7019. return
  7020. else:
  7021. self.export_svg(name, filename)
  7022. if self.defaults["global_open_style"] is False:
  7023. self.app.file_opened.emit("SVG", filename)
  7024. self.app.file_saved.emit("SVG", filename)
  7025. def on_file_exportpng(self):
  7026. self.app.log.debug("on_file_exportpng()")
  7027. date = str(datetime.today()).rpartition('.')[0]
  7028. date = ''.join(c for c in date if c not in ':-')
  7029. date = date.replace(' ', '_')
  7030. data = None
  7031. if self.app.is_legacy is False:
  7032. image = _screenshot(alpha=False)
  7033. data = np.asarray(image)
  7034. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7035. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  7036. return
  7037. filter_ = "PNG File (*.png);;All Files (*.*)"
  7038. try:
  7039. filename, _f = FCFileSaveDialog.get_saved_filename(
  7040. caption=_("Export PNG Image"),
  7041. directory=self.app.get_last_save_folder() + '/png_' + date,
  7042. ext_filter=filter_)
  7043. except TypeError:
  7044. filename, _f = FCFileSaveDialog.get_saved_filename(
  7045. caption=_("Export PNG Image"),
  7046. ext_filter=filter_)
  7047. filename = str(filename)
  7048. if filename == "":
  7049. self.inform.emit(_("Cancelled."))
  7050. return
  7051. else:
  7052. if self.app.is_legacy is False:
  7053. write_png(filename, data)
  7054. else:
  7055. self.app.plotcanvas.figure.savefig(filename)
  7056. if self.defaults["global_open_style"] is False:
  7057. self.app.file_opened.emit("png", filename)
  7058. self.app.file_saved.emit("png", filename)
  7059. def on_file_savegerber(self):
  7060. """
  7061. Callback for menu item in Project context menu.
  7062. :return: None
  7063. """
  7064. self.app.log.debug("on_file_savegerber()")
  7065. obj = self.app.collection.get_active()
  7066. if obj is None:
  7067. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7068. return
  7069. # Check for more compatible types and add as required
  7070. if not isinstance(obj, GerberObject):
  7071. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7072. return
  7073. name = self.app.collection.get_active().options["name"]
  7074. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7075. try:
  7076. filename, _f = FCFileSaveDialog.get_saved_filename(
  7077. caption="Save Gerber source file",
  7078. directory=self.app.get_last_save_folder() + '/' + name,
  7079. ext_filter=_filter)
  7080. except TypeError:
  7081. filename, _f = FCFileSaveDialog.get_saved_filename(
  7082. caption=_("Save Gerber source file"),
  7083. ext_filter=_filter)
  7084. filename = str(filename)
  7085. if filename == "":
  7086. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7087. return
  7088. else:
  7089. self.save_source_file(name, filename)
  7090. if self.defaults["global_open_style"] is False:
  7091. self.app.file_opened.emit("Gerber", filename)
  7092. self.app.file_saved.emit("Gerber", filename)
  7093. def on_file_savescript(self):
  7094. """
  7095. Callback for menu item in Project context menu.
  7096. :return: None
  7097. """
  7098. self.app.log.debug("on_file_savescript()")
  7099. obj = self.app.collection.get_active()
  7100. if obj is None:
  7101. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7102. return
  7103. # Check for more compatible types and add as required
  7104. if not isinstance(obj, ScriptObject):
  7105. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  7106. return
  7107. name = self.app.collection.get_active().options["name"]
  7108. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7109. try:
  7110. filename, _f = FCFileSaveDialog.get_saved_filename(
  7111. caption="Save Script source file",
  7112. directory=self.app.get_last_save_folder() + '/' + name,
  7113. ext_filter=_filter)
  7114. except TypeError:
  7115. filename, _f = FCFileSaveDialog.get_saved_filename(
  7116. caption=_("Save Script source file"),
  7117. ext_filter=_filter)
  7118. filename = str(filename)
  7119. if filename == "":
  7120. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7121. return
  7122. else:
  7123. self.save_source_file(name, filename)
  7124. if self.defaults["global_open_style"] is False:
  7125. self.app.file_opened.emit("Script", filename)
  7126. self.app.file_saved.emit("Script", filename)
  7127. def on_file_savedocument(self):
  7128. """
  7129. Callback for menu item in Project context menu.
  7130. :return: None
  7131. """
  7132. self.app.log.debug("on_file_savedocument()")
  7133. obj = self.app.collection.get_active()
  7134. if obj is None:
  7135. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7136. return
  7137. # Check for more compatible types and add as required
  7138. if not isinstance(obj, ScriptObject):
  7139. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  7140. return
  7141. name = self.app.collection.get_active().options["name"]
  7142. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7143. try:
  7144. filename, _f = FCFileSaveDialog.get_saved_filename(
  7145. caption="Save Document source file",
  7146. directory=self.app.get_last_save_folder() + '/' + name,
  7147. ext_filter=_filter)
  7148. except TypeError:
  7149. filename, _f = FCFileSaveDialog.get_saved_filename(
  7150. caption=_("Save Document source file"),
  7151. ext_filter=_filter)
  7152. filename = str(filename)
  7153. if filename == "":
  7154. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7155. return
  7156. else:
  7157. self.save_source_file(name, filename)
  7158. if self.defaults["global_open_style"] is False:
  7159. self.app.file_opened.emit("Document", filename)
  7160. self.app.file_saved.emit("Document", filename)
  7161. def on_file_saveexcellon(self):
  7162. """
  7163. Callback for menu item in project context menu.
  7164. :return: None
  7165. """
  7166. self.app.log.debug("on_file_saveexcellon()")
  7167. obj = self.app.collection.get_active()
  7168. if obj is None:
  7169. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7170. return
  7171. # Check for more compatible types and add as required
  7172. if not isinstance(obj, ExcellonObject):
  7173. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7174. return
  7175. name = self.app.collection.get_active().options["name"]
  7176. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7177. try:
  7178. filename, _f = FCFileSaveDialog.get_saved_filename(
  7179. caption=_("Save Excellon source file"),
  7180. directory=self.app.get_last_save_folder() + '/' + name,
  7181. ext_filter=_filter)
  7182. except TypeError:
  7183. filename, _f = FCFileSaveDialog.get_saved_filename(
  7184. caption=_("Save Excellon source file"), ext_filter=_filter)
  7185. filename = str(filename)
  7186. if filename == "":
  7187. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7188. return
  7189. else:
  7190. self.save_source_file(name, filename)
  7191. if self.defaults["global_open_style"] is False:
  7192. self.app.file_opened.emit("Excellon", filename)
  7193. self.app.file_saved.emit("Excellon", filename)
  7194. def on_file_exportexcellon(self):
  7195. """
  7196. Callback for menu item File->Export->Excellon.
  7197. :return: None
  7198. """
  7199. self.app.log.debug("on_file_exportexcellon()")
  7200. obj = self.app.collection.get_active()
  7201. if obj is None:
  7202. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7203. return
  7204. # Check for more compatible types and add as required
  7205. if not isinstance(obj, ExcellonObject):
  7206. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7207. return
  7208. name = self.app.collection.get_active().options["name"]
  7209. _filter = self.defaults["excellon_save_filters"]
  7210. try:
  7211. filename, _f = FCFileSaveDialog.get_saved_filename(
  7212. caption=_("Export Excellon"),
  7213. directory=self.app.get_last_save_folder() + '/' + name,
  7214. ext_filter=_filter)
  7215. except TypeError:
  7216. filename, _f = FCFileSaveDialog.get_saved_filename(
  7217. caption=_("Export Excellon"),
  7218. ext_filter=_filter)
  7219. filename = str(filename)
  7220. if filename == "":
  7221. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7222. return
  7223. else:
  7224. used_extension = filename.rpartition('.')[2]
  7225. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7226. self.export_excellon(name, filename)
  7227. if self.defaults["global_open_style"] is False:
  7228. self.app.file_opened.emit("Excellon", filename)
  7229. self.app.file_saved.emit("Excellon", filename)
  7230. def on_file_exportgerber(self):
  7231. """
  7232. Callback for menu item File->Export->Gerber.
  7233. :return: None
  7234. """
  7235. App.log.debug("on_file_exportgerber()")
  7236. obj = self.app.collection.get_active()
  7237. if obj is None:
  7238. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7239. return
  7240. # Check for more compatible types and add as required
  7241. if not isinstance(obj, GerberObject):
  7242. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7243. return
  7244. name = self.app.collection.get_active().options["name"]
  7245. _filter_ = self.defaults['gerber_save_filters']
  7246. try:
  7247. filename, _f = FCFileSaveDialog.get_saved_filename(
  7248. caption=_("Export Gerber"),
  7249. directory=self.app.get_last_save_folder() + '/' + name,
  7250. ext_filter=_filter_)
  7251. except TypeError:
  7252. filename, _f = FCFileSaveDialog.get_saved_filename(
  7253. caption=_("Export Gerber"),
  7254. ext_filter=_filter_)
  7255. filename = str(filename)
  7256. if filename == "":
  7257. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7258. return
  7259. else:
  7260. used_extension = filename.rpartition('.')[2]
  7261. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7262. self.export_gerber(name, filename)
  7263. if self.defaults["global_open_style"] is False:
  7264. self.app.file_opened.emit("Gerber", filename)
  7265. self.app.file_saved.emit("Gerber", filename)
  7266. def on_file_exportdxf(self):
  7267. """
  7268. Callback for menu item File->Export DXF.
  7269. :return: None
  7270. """
  7271. App.log.debug("on_file_exportdxf()")
  7272. obj = self.app.collection.get_active()
  7273. if obj is None:
  7274. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected."))
  7275. msg = _("Please Select a Geometry object to export")
  7276. msgbox = QtWidgets.QMessageBox()
  7277. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7278. msgbox.setInformativeText(msg)
  7279. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7280. msgbox.setDefaultButton(bt_ok)
  7281. msgbox.exec_()
  7282. return
  7283. # Check for more compatible types and add as required
  7284. if not isinstance(obj, GeometryObject):
  7285. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7286. msgbox = QtWidgets.QMessageBox()
  7287. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7288. msgbox.setInformativeText(msg)
  7289. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7290. msgbox.setDefaultButton(bt_ok)
  7291. msgbox.exec_()
  7292. return
  7293. name = self.app.collection.get_active().options["name"]
  7294. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7295. try:
  7296. filename, _f = FCFileSaveDialog.get_saved_filename(
  7297. caption=_("Export DXF"),
  7298. directory=self.app.get_last_save_folder() + '/' + name,
  7299. ext_filter=_filter_)
  7300. except TypeError:
  7301. filename, _f = FCFileSaveDialog.get_saved_filename(
  7302. caption=_("Export DXF"),
  7303. ext_filter=_filter_)
  7304. filename = str(filename)
  7305. if filename == "":
  7306. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7307. return
  7308. else:
  7309. self.export_dxf(name, filename)
  7310. if self.defaults["global_open_style"] is False:
  7311. self.app.file_opened.emit("DXF", filename)
  7312. self.app.file_saved.emit("DXF", filename)
  7313. def on_file_importsvg(self, type_of_obj):
  7314. """
  7315. Callback for menu item File->Import SVG.
  7316. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7317. :type type_of_obj: str
  7318. :return: None
  7319. """
  7320. self.app.log.debug("on_file_importsvg()")
  7321. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7322. try:
  7323. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7324. directory=self.app.get_last_folder(),
  7325. filter=_filter_)
  7326. except TypeError:
  7327. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7328. filter=_filter_)
  7329. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7330. type_of_obj = "geometry"
  7331. filenames = [str(filename) for filename in filenames]
  7332. if len(filenames) == 0:
  7333. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7334. else:
  7335. for filename in filenames:
  7336. if filename != '':
  7337. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7338. def on_file_importdxf(self, type_of_obj):
  7339. """
  7340. Callback for menu item File->Import DXF.
  7341. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7342. :type type_of_obj: str
  7343. :return: None
  7344. """
  7345. self.app.log.debug("on_file_importdxf()")
  7346. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7347. try:
  7348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7349. directory=self.app.get_last_folder(),
  7350. filter=_filter_)
  7351. except TypeError:
  7352. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7353. filter=_filter_)
  7354. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7355. type_of_obj = "geometry"
  7356. filenames = [str(filename) for filename in filenames]
  7357. if len(filenames) == 0:
  7358. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7359. else:
  7360. for filename in filenames:
  7361. if filename != '':
  7362. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7363. def on_file_new_click(self):
  7364. """
  7365. Callback for menu item File -> New.
  7366. Executed on clicking the Menu -> File -> New Project
  7367. :return:
  7368. """
  7369. if self.app.collection.get_list() and self.app.should_we_save:
  7370. msgbox = QtWidgets.QMessageBox()
  7371. # msgbox.setText("<B>Save changes ...</B>")
  7372. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7373. "Creating a New project will delete them.\n"
  7374. "Do you want to Save the project?"))
  7375. msgbox.setWindowTitle(_("Save changes"))
  7376. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7377. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7378. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7379. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7380. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7381. msgbox.setDefaultButton(bt_yes)
  7382. msgbox.exec_()
  7383. response = msgbox.clickedButton()
  7384. if response == bt_yes:
  7385. self.on_file_saveprojectas()
  7386. elif response == bt_cancel:
  7387. return
  7388. elif response == bt_no:
  7389. self.on_file_new()
  7390. else:
  7391. self.on_file_new()
  7392. self.inform.emit('[success] %s...' % _("New Project created"))
  7393. def on_file_new(self, cli=None):
  7394. """
  7395. Returns the application to its startup state. This method is thread-safe.
  7396. :param cli: Boolean. If True this method was run from command line
  7397. :return: None
  7398. """
  7399. self.defaults.report_usage("on_file_new")
  7400. # Remove everything from memory
  7401. self.app.log.debug("on_file_new()")
  7402. # close any editor that might be open
  7403. if self.app.call_source != 'app':
  7404. self.app.editor2object(cleanup=True)
  7405. # ## EDITOR section
  7406. self.app.geo_editor = AppGeoEditor(self.app)
  7407. self.app.exc_editor = AppExcEditor(self.app)
  7408. self.app.grb_editor = AppGerberEditor(self.app)
  7409. # Clear pool
  7410. self.app.clear_pool()
  7411. for obj in self.app.collection.get_list():
  7412. # delete shapes left drawn from mark shape_collections, if any
  7413. if isinstance(obj, GerberObject):
  7414. try:
  7415. obj.mark_shapes_storage.clear()
  7416. obj.mark_shapes.clear(update=True)
  7417. obj.mark_shapes.enabled = False
  7418. except AttributeError:
  7419. pass
  7420. # also delete annotation shapes, if any
  7421. elif isinstance(obj, CNCJobObject):
  7422. try:
  7423. obj.text_col.enabled = False
  7424. del obj.text_col
  7425. obj.annotation.clear(update=True)
  7426. del obj.annotation
  7427. except AttributeError:
  7428. pass
  7429. # delete the exclusion areas
  7430. self.app.exc_areas.clear_shapes()
  7431. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7432. self.app.shell.init_tcl()
  7433. # delete any selection shape on canvas
  7434. self.app.delete_selection_shape()
  7435. # delete all FlatCAM objects
  7436. self.app.collection.delete_all()
  7437. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7438. self.app.setup_default_properties_tab()
  7439. # Clear project filename
  7440. self.app.project_filename = None
  7441. # Load the application defaults
  7442. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7443. # Re-fresh project options
  7444. self.app.on_options_app2project()
  7445. # Init FlatCAMTools
  7446. self.app.init_tools()
  7447. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7448. if cli is None:
  7449. # we need to go in reverse because once we remove a tab then the index changes
  7450. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7451. # and so on. Therefore the deletion should be done in reverse
  7452. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7453. for index in range(wdg_count, -1, -1):
  7454. try:
  7455. self.app.ui.plot_tab_area.closeTab(index)
  7456. except Exception as e:
  7457. log.debug("App.on_file_new() --> %s" % str(e))
  7458. # # And then add again the Plot Area
  7459. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7460. self.app.ui.plot_tab_area.protectTab(0)
  7461. # take the focus of the Notebook on Project Tab.
  7462. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7463. self.app.ui.set_ui_title(name=_("New Project - Not saved"))
  7464. def on_filenewscript(self, silent=False):
  7465. """
  7466. Will create a new script file and open it in the Code Editor
  7467. :param silent: if True will not display status messages
  7468. :return: None
  7469. """
  7470. if silent is False:
  7471. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7472. # hide coordinates toolbars in the infobar while in DB
  7473. self.app.ui.coords_toolbar.hide()
  7474. self.app.ui.delta_coords_toolbar.hide()
  7475. self.app.app_obj.new_script_object()
  7476. def on_fileopenscript(self, name=None, silent=False):
  7477. """
  7478. Will open a Tcl script file into the Code Editor
  7479. :param silent: if True will not display status messages
  7480. :param name: name of a Tcl script file to open
  7481. :return: None
  7482. """
  7483. self.app.log.debug("on_fileopenscript()")
  7484. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7485. "All Files (*.*)"
  7486. if name:
  7487. filenames = [name]
  7488. else:
  7489. try:
  7490. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7491. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7492. except TypeError:
  7493. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7494. if len(filenames) == 0:
  7495. if silent is False:
  7496. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7497. else:
  7498. for filename in filenames:
  7499. if filename != '':
  7500. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7501. def on_fileopenscript_example(self, name=None, silent=False):
  7502. """
  7503. Will open a Tcl script file into the Code Editor
  7504. :param silent: if True will not display status messages
  7505. :param name: name of a Tcl script file to open
  7506. :return:
  7507. """
  7508. self.app.log.debug("on_fileopenscript_example()")
  7509. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7510. "All Files (*.*)"
  7511. # test if the app was frozen and choose the path for the configuration file
  7512. if getattr(sys, "frozen", False) is True:
  7513. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7514. else:
  7515. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7516. if name:
  7517. filenames = [name]
  7518. else:
  7519. try:
  7520. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7521. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7522. except TypeError:
  7523. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7524. if len(filenames) == 0:
  7525. if silent is False:
  7526. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7527. else:
  7528. for filename in filenames:
  7529. if filename != '':
  7530. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7531. def on_filerunscript(self, name=None, silent=False):
  7532. """
  7533. File menu callback for loading and running a TCL script.
  7534. :param silent: if True will not display status messages
  7535. :param name: name of a Tcl script file to be run by FlatCAM
  7536. :return: None
  7537. """
  7538. self.app.log.debug("on_file_runscript()")
  7539. if name:
  7540. filename = name
  7541. if self.app.cmd_line_headless != 1:
  7542. self.splash.showMessage('%s: %ssec\n%s' %
  7543. (_("Canvas initialization started.\n"
  7544. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7545. _("Executing ScriptObject file.")
  7546. ),
  7547. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7548. color=QtGui.QColor("gray"))
  7549. else:
  7550. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7551. "All Files (*.*)"
  7552. try:
  7553. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7554. directory=self.app.get_last_folder(),
  7555. filter=_filter_)
  7556. except TypeError:
  7557. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7558. # The Qt methods above will return a QString which can cause problems later.
  7559. # So far json.dump() will fail to serialize it.
  7560. filename = str(filename)
  7561. if filename == "":
  7562. if silent is False:
  7563. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7564. else:
  7565. if self.app.cmd_line_headless != 1:
  7566. if self.app.ui.shell_dock.isHidden():
  7567. self.app.ui.shell_dock.show()
  7568. try:
  7569. with open(filename, "r") as tcl_script:
  7570. cmd_line_shellfile_content = tcl_script.read()
  7571. if self.app.cmd_line_headless != 1:
  7572. self.app.shell.exec_command(cmd_line_shellfile_content)
  7573. else:
  7574. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7575. if silent is False:
  7576. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7577. except Exception as e:
  7578. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7579. sys.exit(2)
  7580. def on_file_saveproject(self, silent=False):
  7581. """
  7582. Callback for menu item File->Save Project. Saves the project to
  7583. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7584. if set to None. The project is saved by calling ``self.save_project()``.
  7585. :param silent: if True will not display status messages
  7586. :return: None
  7587. """
  7588. if self.app.project_filename is None:
  7589. self.on_file_saveprojectas()
  7590. else:
  7591. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7592. if self.defaults["global_open_style"] is False:
  7593. self.app.file_opened.emit("project", self.app.project_filename)
  7594. self.app.file_saved.emit("project", self.app.project_filename)
  7595. self.app.ui.set_ui_title(name=self.app.project_filename)
  7596. self.app.should_we_save = False
  7597. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7598. """
  7599. Callback for menu item File->Save Project As... Opens a file
  7600. chooser and saves the project to the given file via
  7601. ``self.save_project()``.
  7602. :param make_copy if to be create a copy of the project; boolean
  7603. :param use_thread: if to be run in a separate thread; boolean
  7604. :param quit_action: if to be followed by quiting the application; boolean
  7605. :return: None
  7606. """
  7607. date = str(datetime.today()).rpartition('.')[0]
  7608. date = ''.join(c for c in date if c not in ':-')
  7609. date = date.replace(' ', '_')
  7610. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7611. try:
  7612. filename, _f = FCFileSaveDialog.get_saved_filename(
  7613. caption=_("Save Project As ..."),
  7614. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7615. proj=_("Project")),
  7616. ext_filter=filter_
  7617. )
  7618. except TypeError:
  7619. filename, _f = FCFileSaveDialog.get_saved_filename(
  7620. caption=_("Save Project As ..."),
  7621. ext_filter=filter_)
  7622. filename = str(filename)
  7623. if filename == '':
  7624. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7625. return
  7626. if use_thread is True:
  7627. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7628. else:
  7629. self.save_project(filename, quit_action)
  7630. # self.save_project(filename)
  7631. if self.defaults["global_open_style"] is False:
  7632. self.app.file_opened.emit("project", filename)
  7633. self.app.file_saved.emit("project", filename)
  7634. if not make_copy:
  7635. self.app.project_filename = filename
  7636. self.app.ui.set_ui_title(name=self.app.project_filename)
  7637. self.app.should_we_save = False
  7638. def on_file_save_objects_pdf(self, use_thread=True):
  7639. date = str(datetime.today()).rpartition('.')[0]
  7640. date = ''.join(c for c in date if c not in ':-')
  7641. date = date.replace(' ', '_')
  7642. try:
  7643. obj_selection = self.app.collection.get_selected()
  7644. if len(obj_selection) == 1:
  7645. obj_name = str(obj_selection[0].options['name'])
  7646. else:
  7647. obj_name = _("FlatCAM objects print")
  7648. except AttributeError as err:
  7649. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7650. self.inform.emit('[ERROR_NOTCL] %s' % _("No object is selected."))
  7651. return
  7652. if not obj_selection:
  7653. self.inform.emit('[ERROR_NOTCL] %s' % _("No object is selected."))
  7654. return
  7655. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7656. try:
  7657. filename, _f = FCFileSaveDialog.get_saved_filename(
  7658. caption=_("Save Object as PDF ..."),
  7659. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7660. obj_name=obj_name,
  7661. date=date),
  7662. ext_filter=filter_
  7663. )
  7664. except TypeError:
  7665. filename, _f = FCFileSaveDialog.get_saved_filename(
  7666. caption=_("Save Object as PDF ..."),
  7667. ext_filter=filter_)
  7668. filename = str(filename)
  7669. if filename == '':
  7670. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7671. return
  7672. if use_thread is True:
  7673. self.app.proc_container.new(_("Printing PDF ..."))
  7674. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7675. else:
  7676. self.save_pdf(filename, obj_selection)
  7677. # self.save_project(filename)
  7678. if self.defaults["global_open_style"] is False:
  7679. self.app.file_opened.emit("pdf", filename)
  7680. self.app.file_saved.emit("pdf", filename)
  7681. def save_pdf(self, file_name, obj_selection):
  7682. p_size = self.defaults['global_workspaceT']
  7683. orientation = self.defaults['global_workspace_orientation']
  7684. color = 'black'
  7685. transparency_level = 1.0
  7686. self.pagesize.update(
  7687. {
  7688. 'Bounds': None,
  7689. 'A0': (841 * mm, 1189 * mm),
  7690. 'A1': (594 * mm, 841 * mm),
  7691. 'A2': (420 * mm, 594 * mm),
  7692. 'A3': (297 * mm, 420 * mm),
  7693. 'A4': (210 * mm, 297 * mm),
  7694. 'A5': (148 * mm, 210 * mm),
  7695. 'A6': (105 * mm, 148 * mm),
  7696. 'A7': (74 * mm, 105 * mm),
  7697. 'A8': (52 * mm, 74 * mm),
  7698. 'A9': (37 * mm, 52 * mm),
  7699. 'A10': (26 * mm, 37 * mm),
  7700. 'B0': (1000 * mm, 1414 * mm),
  7701. 'B1': (707 * mm, 1000 * mm),
  7702. 'B2': (500 * mm, 707 * mm),
  7703. 'B3': (353 * mm, 500 * mm),
  7704. 'B4': (250 * mm, 353 * mm),
  7705. 'B5': (176 * mm, 250 * mm),
  7706. 'B6': (125 * mm, 176 * mm),
  7707. 'B7': (88 * mm, 125 * mm),
  7708. 'B8': (62 * mm, 88 * mm),
  7709. 'B9': (44 * mm, 62 * mm),
  7710. 'B10': (31 * mm, 44 * mm),
  7711. 'C0': (917 * mm, 1297 * mm),
  7712. 'C1': (648 * mm, 917 * mm),
  7713. 'C2': (458 * mm, 648 * mm),
  7714. 'C3': (324 * mm, 458 * mm),
  7715. 'C4': (229 * mm, 324 * mm),
  7716. 'C5': (162 * mm, 229 * mm),
  7717. 'C6': (114 * mm, 162 * mm),
  7718. 'C7': (81 * mm, 114 * mm),
  7719. 'C8': (57 * mm, 81 * mm),
  7720. 'C9': (40 * mm, 57 * mm),
  7721. 'C10': (28 * mm, 40 * mm),
  7722. # American paper sizes
  7723. 'LETTER': (8.5 * inch, 11 * inch),
  7724. 'LEGAL': (8.5 * inch, 14 * inch),
  7725. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7726. # From https://en.wikipedia.org/wiki/Paper_size
  7727. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7728. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7729. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7730. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7731. 'LEDGER': (17 * inch, 11 * inch),
  7732. }
  7733. )
  7734. exported_svg = []
  7735. for obj in obj_selection:
  7736. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7737. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7738. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7739. color = obj.fill_color[:-2]
  7740. transparency_level = obj.fill_color[-2:]
  7741. elif obj.kind.lower() == 'geometry':
  7742. color = self.defaults["global_draw_color"]
  7743. # Change the attributes of the exported SVG
  7744. # We don't need stroke-width
  7745. # We set opacity to maximum
  7746. # We set the colour to WHITE
  7747. root = ET.fromstring(svg_obj)
  7748. for child in root:
  7749. child.set('fill', str(color))
  7750. child.set('opacity', str(transparency_level))
  7751. child.set('stroke', str(color))
  7752. exported_svg.append(ET.tostring(root))
  7753. xmin = Inf
  7754. ymin = Inf
  7755. xmax = -Inf
  7756. ymax = -Inf
  7757. for obj in obj_selection:
  7758. try:
  7759. gxmin, gymin, gxmax, gymax = obj.bounds()
  7760. xmin = min([xmin, gxmin])
  7761. ymin = min([ymin, gymin])
  7762. xmax = max([xmax, gxmax])
  7763. ymax = max([ymax, gymax])
  7764. except Exception as e:
  7765. self.app.log.warning(
  7766. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7767. # Determine bounding area for svg export
  7768. bounds = [xmin, ymin, xmax, ymax]
  7769. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7770. # This contain the measure units
  7771. uom = obj_selection[0].units.lower()
  7772. # Define a boundary around SVG of about 1.0mm (~39mils)
  7773. if uom in "mm":
  7774. boundary = 1.0
  7775. else:
  7776. boundary = 0.0393701
  7777. # Convert everything to strings for use in the xml doc
  7778. svgwidth = str(size[0] + (2 * boundary))
  7779. svgheight = str(size[1] + (2 * boundary))
  7780. minx = str(bounds[0] - boundary)
  7781. miny = str(bounds[1] + boundary + size[1])
  7782. # Add a SVG Header and footer to the svg output from shapely
  7783. # The transform flips the Y Axis so that everything renders
  7784. # properly within svg apps such as inkscape
  7785. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7786. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7787. svg_header += 'width="' + svgwidth + uom + '" '
  7788. svg_header += 'height="' + svgheight + uom + '" '
  7789. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7790. svg_header += '>'
  7791. svg_header += '<g transform="scale(1,-1)">'
  7792. svg_footer = '</g> </svg>'
  7793. svg_elem = str(svg_header)
  7794. for svg_item in exported_svg:
  7795. svg_elem += str(svg_item)
  7796. svg_elem += str(svg_footer)
  7797. # Parse the xml through a xml parser just to add line feeds
  7798. # and to make it look more pretty for the output
  7799. doc = parse_xml_string(svg_elem)
  7800. doc_final = doc.toprettyxml()
  7801. try:
  7802. if self.defaults['units'].upper() == 'IN':
  7803. unit = inch
  7804. else:
  7805. unit = mm
  7806. doc_final = StringIO(doc_final)
  7807. drawing = svg2rlg(doc_final)
  7808. if p_size == 'Bounds':
  7809. renderPDF.drawToFile(drawing, file_name)
  7810. else:
  7811. if orientation == 'p':
  7812. page_size = portrait(self.pagesize[p_size])
  7813. else:
  7814. page_size = landscape(self.pagesize[p_size])
  7815. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7816. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7817. renderPDF.draw(drawing, my_canvas, 0, 0)
  7818. my_canvas.save()
  7819. except Exception as e:
  7820. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7821. return 'fail'
  7822. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7823. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7824. """
  7825. Exports a Geometry Object to an SVG file.
  7826. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7827. :param filename: Path to the SVG file to save to.
  7828. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7829. :return:
  7830. """
  7831. if filename is None:
  7832. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7833. is not None else self.defaults["global_last_folder"]
  7834. self.app.log.debug("export_svg()")
  7835. try:
  7836. obj = self.app.collection.get_by_name(str(obj_name))
  7837. except Exception:
  7838. return 'fail'
  7839. with self.app.proc_container.new(_("Exporting ...")):
  7840. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7841. # Determine bounding area for svg export
  7842. bounds = obj.bounds()
  7843. size = obj.size()
  7844. # Convert everything to strings for use in the xml doc
  7845. svgwidth = str(size[0])
  7846. svgheight = str(size[1])
  7847. minx = str(bounds[0])
  7848. miny = str(bounds[1] - size[1])
  7849. uom = obj.units.lower()
  7850. # Add a SVG Header and footer to the svg output from shapely
  7851. # The transform flips the Y Axis so that everything renders
  7852. # properly within svg apps such as inkscape
  7853. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7854. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7855. svg_header += 'width="' + svgwidth + uom + '" '
  7856. svg_header += 'height="' + svgheight + uom + '" '
  7857. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7858. svg_header += '<g transform="scale(1,-1)">'
  7859. svg_footer = '</g> </svg>'
  7860. svg_elem = svg_header + exported_svg + svg_footer
  7861. # Parse the xml through a xml parser just to add line feeds
  7862. # and to make it look more pretty for the output
  7863. svgcode = parse_xml_string(svg_elem)
  7864. svgcode = svgcode.toprettyxml()
  7865. try:
  7866. with open(filename, 'w') as fp:
  7867. fp.write(svgcode)
  7868. except PermissionError:
  7869. self.inform.emit('[WARNING] %s' %
  7870. _("Permission denied, saving not possible.\n"
  7871. "Most likely another app is holding the file open and not accessible."))
  7872. return 'fail'
  7873. if self.defaults["global_open_style"] is False:
  7874. self.app.file_opened.emit("SVG", filename)
  7875. self.app.file_saved.emit("SVG", filename)
  7876. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7877. def on_import_preferences(self):
  7878. """
  7879. Loads the application default settings from a saved file into
  7880. ``self.defaults`` dictionary.
  7881. :return: None
  7882. """
  7883. self.app.log.debug("App.on_import_preferences()")
  7884. # Show file chooser
  7885. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7886. try:
  7887. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7888. directory=self.app.data_path,
  7889. filter=filter_)
  7890. except TypeError:
  7891. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7892. filter=filter_)
  7893. filename = str(filename)
  7894. if filename == "":
  7895. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7896. return
  7897. # Load in the defaults from the chosen file
  7898. self.defaults.load(filename=filename, inform=self.inform)
  7899. self.app.preferencesUiManager.on_preferences_edited()
  7900. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7901. def on_export_preferences(self):
  7902. """
  7903. Save the defaults dictionary to a file.
  7904. :return: None
  7905. """
  7906. self.app.log.debug("on_export_preferences()")
  7907. # defaults_file_content = None
  7908. # Show file chooser
  7909. date = str(datetime.today()).rpartition('.')[0]
  7910. date = ''.join(c for c in date if c not in ':-')
  7911. date = date.replace(' ', '_')
  7912. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7913. try:
  7914. filename, _f = FCFileSaveDialog.get_saved_filename(
  7915. caption=_("Export FlatCAM Preferences"),
  7916. directory=self.app.data_path + '/preferences_' + date,
  7917. ext_filter=filter__
  7918. )
  7919. except TypeError:
  7920. filename, _f = FCFileSaveDialog.get_saved_filename(
  7921. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7922. filename = str(filename)
  7923. if filename == "":
  7924. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7925. return 'fail'
  7926. # Update options
  7927. self.app.preferencesUiManager.defaults_read_form()
  7928. self.defaults.propagate_defaults()
  7929. # Save update options
  7930. try:
  7931. self.defaults.write(filename=filename)
  7932. except Exception:
  7933. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7934. return
  7935. if self.defaults["global_open_style"] is False:
  7936. self.app.file_opened.emit("preferences", filename)
  7937. self.app.file_saved.emit("preferences", filename)
  7938. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7939. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7940. """
  7941. Exports a Excellon Object to an Excellon file.
  7942. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7943. :param filename: Path to the Excellon file to save to.
  7944. :param local_use:
  7945. :param use_thread: if to be run in a separate thread
  7946. :return:
  7947. """
  7948. if filename is None:
  7949. if self.defaults["global_last_save_folder"]:
  7950. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7951. else:
  7952. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7953. self.app.log.debug("export_excellon()")
  7954. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7955. self.defaults["excellon_exp_decimals"]
  7956. )
  7957. if local_use is None:
  7958. try:
  7959. obj = self.app.collection.get_by_name(str(obj_name))
  7960. except Exception:
  7961. return "Could not retrieve object: %s" % obj_name
  7962. else:
  7963. obj = local_use
  7964. if not isinstance(obj, ExcellonObject):
  7965. self.inform.emit('[ERROR_NOTCL] %s' %
  7966. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7967. return
  7968. # updated units
  7969. eunits = self.defaults["excellon_exp_units"]
  7970. ewhole = self.defaults["excellon_exp_integer"]
  7971. efract = self.defaults["excellon_exp_decimals"]
  7972. ezeros = self.defaults["excellon_exp_zeros"]
  7973. eformat = self.defaults["excellon_exp_format"]
  7974. slot_type = self.defaults["excellon_exp_slot_type"]
  7975. fc_units = self.defaults['units'].upper()
  7976. if fc_units == 'MM':
  7977. factor = 1 if eunits == 'METRIC' else 0.03937
  7978. else:
  7979. factor = 25.4 if eunits == 'METRIC' else 1
  7980. def make_excellon():
  7981. try:
  7982. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7983. header = 'M48\n'
  7984. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7985. (str(self.app.version), str(self.app.version_date))
  7986. header += ';Filename: %s' % str(obj_name) + '\n'
  7987. header += ';Created on : %s' % time_str + '\n'
  7988. if eformat == 'dec':
  7989. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7990. header += eunits + '\n'
  7991. for tool in obj.tools:
  7992. if eunits == 'METRIC':
  7993. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7994. tool=str(tool),
  7995. dec=2)
  7996. else:
  7997. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7998. tool=str(tool),
  7999. dec=4)
  8000. else:
  8001. if ezeros == 'LZ':
  8002. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8003. form='ndec', e_zeros='LZ', factor=factor,
  8004. slot_type=slot_type)
  8005. header += '%s,%s\n' % (eunits, 'LZ')
  8006. header += format_exc
  8007. for tool in obj.tools:
  8008. if eunits == 'METRIC':
  8009. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8010. float(obj.tools[tool]['tooldia']) * factor,
  8011. tool=str(tool),
  8012. dec=2)
  8013. else:
  8014. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8015. float(obj.tools[tool]['tooldia']) * factor,
  8016. tool=str(tool),
  8017. dec=4)
  8018. else:
  8019. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8020. form='ndec', e_zeros='TZ', factor=factor,
  8021. slot_type=slot_type)
  8022. header += '%s,%s\n' % (eunits, 'TZ')
  8023. header += format_exc
  8024. for tool in obj.tools:
  8025. if eunits == 'METRIC':
  8026. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8027. float(obj.tools[tool]['tooldia']) * factor,
  8028. tool=str(tool),
  8029. dec=2)
  8030. else:
  8031. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  8032. float(obj.tools[tool]['tooldia']) * factor,
  8033. tool=str(tool),
  8034. dec=4)
  8035. header += '%\n'
  8036. footer = 'M30\n'
  8037. exported_excellon = header
  8038. exported_excellon += excellon_code
  8039. exported_excellon += footer
  8040. if local_use is None:
  8041. try:
  8042. with open(filename, 'w') as fp:
  8043. fp.write(exported_excellon)
  8044. except PermissionError:
  8045. self.inform.emit('[WARNING] %s' %
  8046. _("Permission denied, saving not possible.\n"
  8047. "Most likely another app is holding the file open and not accessible."))
  8048. return 'fail'
  8049. if self.defaults["global_open_style"] is False:
  8050. self.app.file_opened.emit("Excellon", filename)
  8051. self.app.file_saved.emit("Excellon", filename)
  8052. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  8053. else:
  8054. return exported_excellon
  8055. except Exception as e:
  8056. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8057. return 'fail'
  8058. if use_thread is True:
  8059. with self.app.proc_container.new(_("Exporting ...")):
  8060. def job_thread_exc(app_obj):
  8061. ret = make_excellon()
  8062. if ret == 'fail':
  8063. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8064. return
  8065. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8066. else:
  8067. eret = make_excellon()
  8068. if eret == 'fail':
  8069. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8070. return 'fail'
  8071. if local_use is not None:
  8072. return eret
  8073. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8074. """
  8075. Exports a Gerber Object to an Gerber file.
  8076. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8077. :param filename: Path to the Gerber file to save to.
  8078. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8079. When not None, the value will be the actual Gerber object for which to create
  8080. the Gerber code
  8081. :param use_thread: if to be run in a separate thread
  8082. :return:
  8083. """
  8084. if filename is None:
  8085. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8086. is not None else self.defaults["global_last_folder"]
  8087. self.app.log.debug("export_gerber()")
  8088. if local_use is None:
  8089. try:
  8090. obj = self.app.collection.get_by_name(str(obj_name))
  8091. except Exception:
  8092. return 'fail'
  8093. else:
  8094. obj = local_use
  8095. # updated units
  8096. gunits = self.defaults["gerber_exp_units"]
  8097. gwhole = self.defaults["gerber_exp_integer"]
  8098. gfract = self.defaults["gerber_exp_decimals"]
  8099. gzeros = self.defaults["gerber_exp_zeros"]
  8100. fc_units = self.defaults['units'].upper()
  8101. if fc_units == 'MM':
  8102. factor = 1 if gunits == 'MM' else 0.03937
  8103. else:
  8104. factor = 25.4 if gunits == 'MM' else 1
  8105. def make_gerber():
  8106. try:
  8107. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8108. header = 'G04*\n'
  8109. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8110. (str(self.app.version), str(self.app.version_date))
  8111. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8112. header += 'G04 Created on : %s*' % time_str + '\n'
  8113. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8114. header += "%MO{units}*%\n".format(units=gunits)
  8115. for apid in obj.apertures:
  8116. if obj.apertures[apid]['type'] == 'C':
  8117. header += "%ADD{apid}{type},{size}*%\n".format(
  8118. apid=str(apid),
  8119. type='C',
  8120. size=(factor * obj.apertures[apid]['size'])
  8121. )
  8122. elif obj.apertures[apid]['type'] == 'R':
  8123. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8124. apid=str(apid),
  8125. type='R',
  8126. width=(factor * obj.apertures[apid]['width']),
  8127. height=(factor * obj.apertures[apid]['height'])
  8128. )
  8129. elif obj.apertures[apid]['type'] == 'O':
  8130. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8131. apid=str(apid),
  8132. type='O',
  8133. width=(factor * obj.apertures[apid]['width']),
  8134. height=(factor * obj.apertures[apid]['height'])
  8135. )
  8136. header += '\n'
  8137. # obsolete units but some software may need it
  8138. if gunits == 'IN':
  8139. header += 'G70*\n'
  8140. else:
  8141. header += 'G71*\n'
  8142. # Absolute Mode
  8143. header += 'G90*\n'
  8144. header += 'G01*\n'
  8145. # positive polarity
  8146. header += '%LPD*%\n'
  8147. footer = 'M02*\n'
  8148. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8149. exported_gerber = header
  8150. exported_gerber += gerber_code
  8151. exported_gerber += footer
  8152. if local_use is None:
  8153. try:
  8154. with open(filename, 'w') as fp:
  8155. fp.write(exported_gerber)
  8156. except PermissionError:
  8157. self.inform.emit('[WARNING] %s' %
  8158. _("Permission denied, saving not possible.\n"
  8159. "Most likely another app is holding the file open and not accessible."))
  8160. return 'fail'
  8161. if self.defaults["global_open_style"] is False:
  8162. self.app.file_opened.emit("Gerber", filename)
  8163. self.app.file_saved.emit("Gerber", filename)
  8164. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8165. else:
  8166. return exported_gerber
  8167. except Exception as e:
  8168. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8169. return 'fail'
  8170. if use_thread is True:
  8171. with self.app.proc_container.new(_("Exporting ...")):
  8172. def job_thread_grb(app_obj):
  8173. ret = make_gerber()
  8174. if ret == 'fail':
  8175. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8176. return
  8177. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8178. else:
  8179. gret = make_gerber()
  8180. if gret == 'fail':
  8181. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export.'))
  8182. return 'fail'
  8183. if local_use is not None:
  8184. return gret
  8185. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8186. """
  8187. Exports a Geometry Object to an DXF file.
  8188. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8189. :param filename: Path to the DXF file to save to.
  8190. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8191. When not None, the value will be the actual Geometry object for which to create
  8192. the Geometry/DXF code
  8193. :param use_thread: if to be run in a separate thread
  8194. :return:
  8195. """
  8196. if filename is None:
  8197. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8198. is not None else self.defaults["global_last_folder"]
  8199. self.app.log.debug("export_dxf()")
  8200. if local_use is None:
  8201. try:
  8202. obj = self.app.collection.get_by_name(str(obj_name))
  8203. except Exception:
  8204. return 'fail'
  8205. else:
  8206. obj = local_use
  8207. def make_dxf():
  8208. try:
  8209. dxf_code = obj.export_dxf()
  8210. if local_use is None:
  8211. try:
  8212. dxf_code.saveas(filename)
  8213. except PermissionError:
  8214. self.inform.emit('[WARNING] %s' %
  8215. _("Permission denied, saving not possible.\n"
  8216. "Most likely another app is holding the file open and not accessible."))
  8217. return 'fail'
  8218. if self.defaults["global_open_style"] is False:
  8219. self.app.file_opened.emit("DXF", filename)
  8220. self.app.file_saved.emit("DXF", filename)
  8221. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8222. else:
  8223. return dxf_code
  8224. except Exception as e:
  8225. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8226. return 'fail'
  8227. if use_thread is True:
  8228. with self.app.proc_container.new(_("Exporting ...")):
  8229. def job_thread_exc(app_obj):
  8230. ret_dxf_val = make_dxf()
  8231. if ret_dxf_val == 'fail':
  8232. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export.'))
  8233. return
  8234. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8235. else:
  8236. ret = make_dxf()
  8237. if ret == 'fail':
  8238. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export.'))
  8239. return
  8240. if local_use is not None:
  8241. return ret
  8242. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8243. """
  8244. Adds a new Geometry Object to the projects and populates
  8245. it with shapes extracted from the SVG file.
  8246. :param plot: If True then the resulting object will be plotted on canvas
  8247. :param filename: Path to the SVG file.
  8248. :param geo_type: Type of FlatCAM object that will be created from SVG
  8249. :param outname: The name given to the resulting FlatCAM object
  8250. :return:
  8251. """
  8252. self.app.log.debug("App.import_svg()")
  8253. obj_type = ""
  8254. if geo_type is None or geo_type == "geometry":
  8255. obj_type = "geometry"
  8256. elif geo_type == "gerber":
  8257. obj_type = "gerber"
  8258. else:
  8259. self.inform.emit('[ERROR_NOTCL] %s' %
  8260. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8261. return
  8262. units = self.defaults['units'].upper()
  8263. def obj_init(geo_obj, app_obj):
  8264. geo_obj.import_svg(filename, obj_type, units=units)
  8265. geo_obj.multigeo = True
  8266. with open(filename) as f:
  8267. file_content = f.read()
  8268. geo_obj.source_file = file_content
  8269. # appGUI feedback
  8270. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8271. with self.app.proc_container.new('%s ...' % _("Importing")):
  8272. # Object name
  8273. name = outname or filename.split('/')[-1].split('\\')[-1]
  8274. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8275. if ret == 'fail':
  8276. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8277. return 'fail'
  8278. # Register recent file
  8279. self.app.file_opened.emit("svg", filename)
  8280. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8281. """
  8282. Adds a new Geometry Object to the projects and populates
  8283. it with shapes extracted from the DXF file.
  8284. :param filename: Path to the DXF file.
  8285. :param geo_type: Type of FlatCAM object that will be created from DXF
  8286. :param outname: Name for the imported Geometry
  8287. :param plot: If True then the resulting object will be plotted on canvas
  8288. :return:
  8289. """
  8290. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8291. obj_type = ""
  8292. if geo_type is None or geo_type == "geometry":
  8293. obj_type = "geometry"
  8294. elif geo_type == "gerber":
  8295. obj_type = geo_type
  8296. else:
  8297. self.inform.emit('[ERROR_NOTCL] %s' %
  8298. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8299. return
  8300. units = self.defaults['units'].upper()
  8301. def obj_init(geo_obj, app_obj):
  8302. if obj_type == "geometry":
  8303. geo_obj.import_dxf_as_geo(filename, units=units)
  8304. elif obj_type == "gerber":
  8305. geo_obj.import_dxf_as_gerber(filename, units=units)
  8306. else:
  8307. return "fail"
  8308. geo_obj.multigeo = True
  8309. with open(filename) as f:
  8310. file_content = f.read()
  8311. geo_obj.source_file = file_content
  8312. # appGUI feedback
  8313. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8314. with self.app.proc_container.new('%s ...' % _("Importing")):
  8315. # Object name
  8316. name = outname or filename.split('/')[-1].split('\\')[-1]
  8317. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8318. if ret == 'fail':
  8319. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8320. return 'fail'
  8321. # Register recent file
  8322. self.app.file_opened.emit("dxf", filename)
  8323. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8324. """
  8325. Opens a Gerber file, parses it and creates a new object for
  8326. it in the program. Thread-safe.
  8327. :param outname: Name of the resulting object. None causes the
  8328. name to be that of the file. Str.
  8329. :param filename: Gerber file filename
  8330. :type filename: str
  8331. :param plot: boolean, to plot or not the resulting object
  8332. :param from_tcl: True if run from Tcl Shell
  8333. :return: None
  8334. """
  8335. # How the object should be initialized
  8336. def obj_init(gerber_obj, app_obj):
  8337. assert isinstance(gerber_obj, GerberObject), \
  8338. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8339. # Opening the file happens here
  8340. try:
  8341. gerber_obj.parse_file(filename)
  8342. except IOError:
  8343. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8344. return "fail"
  8345. except ParseError as err:
  8346. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8347. app_obj.log.error(str(err))
  8348. return "fail"
  8349. except Exception as e:
  8350. log.debug("App.open_gerber() --> %s" % str(e))
  8351. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8352. msg += traceback.format_exc()
  8353. app_obj.inform.emit(msg)
  8354. return "fail"
  8355. if gerber_obj.is_empty():
  8356. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8357. _("Object is not Gerber file or empty. Aborting object creation."))
  8358. return "fail"
  8359. self.app.log.debug("open_gerber()")
  8360. with self.app.proc_container.new(_("Opening ...")):
  8361. # Object name
  8362. name = outname or filename.split('/')[-1].split('\\')[-1]
  8363. # # ## Object creation # ##
  8364. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8365. if ret_val == 'fail':
  8366. if from_tcl:
  8367. filename = self.defaults['global_tcl_path'] + '/' + name
  8368. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8369. if ret_val == 'fail':
  8370. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8371. return 'fail'
  8372. # Register recent file
  8373. self.app.file_opened.emit("gerber", filename)
  8374. # appGUI feedback
  8375. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8376. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8377. """
  8378. Opens an Excellon file, parses it and creates a new object for
  8379. it in the program. Thread-safe.
  8380. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8381. :param filename: Excellon file filename
  8382. :type filename: str
  8383. :param plot: boolean, to plot or not the resulting object
  8384. :param from_tcl: True if run from Tcl Shell
  8385. :return: None
  8386. """
  8387. self.app.log.debug("open_excellon()")
  8388. # How the object should be initialized
  8389. def obj_init(excellon_obj, app_obj):
  8390. try:
  8391. ret = excellon_obj.parse_file(filename=filename)
  8392. if ret == "fail":
  8393. app_obj.log.debug("Excellon parsing failed.")
  8394. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8395. return "fail"
  8396. except IOError:
  8397. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8398. app_obj.log.debug("Could not open Excellon object.")
  8399. return "fail"
  8400. except Exception:
  8401. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8402. msg += traceback.format_exc()
  8403. app_obj.inform.emit(msg)
  8404. return "fail"
  8405. ret = excellon_obj.create_geometry()
  8406. if ret == 'fail':
  8407. app_obj.log.debug("Could not create geometry for Excellon object.")
  8408. return "fail"
  8409. for tool in excellon_obj.tools:
  8410. if excellon_obj.tools[tool]['solid_geometry']:
  8411. return
  8412. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8413. return "fail"
  8414. with self.app.proc_container.new(_("Opening ...")):
  8415. # Object name
  8416. name = outname or filename.split('/')[-1].split('\\')[-1]
  8417. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8418. if ret_val == 'fail':
  8419. if from_tcl:
  8420. filename = self.defaults['global_tcl_path'] + '/' + name
  8421. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8422. if ret_val == 'fail':
  8423. self.inform.emit('[ERROR_NOTCL] %s' %
  8424. _('Open Excellon file failed. Probable not an Excellon file.'))
  8425. return
  8426. # Register recent file
  8427. self.app.file_opened.emit("excellon", filename)
  8428. # appGUI feedback
  8429. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8430. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8431. """
  8432. Opens a G-gcode file, parses it and creates a new object for
  8433. it in the program. Thread-safe.
  8434. :param filename: G-code file filename
  8435. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8436. :param force_parsing:
  8437. :param plot: If True plot the object on canvas
  8438. :param from_tcl: True if run from Tcl Shell
  8439. :return: None
  8440. """
  8441. self.app.log.debug("open_gcode()")
  8442. # How the object should be initialized
  8443. def obj_init(job_obj, app_obj_):
  8444. """
  8445. :param job_obj: the resulting object
  8446. :type app_obj_: App
  8447. """
  8448. assert isinstance(app_obj_, App), \
  8449. "Initializer expected App, got %s" % type(app_obj_)
  8450. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8451. try:
  8452. f = open(filename)
  8453. gcode = f.read()
  8454. f.close()
  8455. except IOError:
  8456. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8457. return "fail"
  8458. job_obj.gcode = gcode
  8459. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8460. if gcode_ret == "fail":
  8461. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8462. return "fail"
  8463. job_obj.create_geometry()
  8464. with self.app.proc_container.new(_("Opening ...")):
  8465. # Object name
  8466. name = outname or filename.split('/')[-1].split('\\')[-1]
  8467. # New object creation and file processing
  8468. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8469. if ret_val == 'fail':
  8470. if from_tcl:
  8471. filename = self.defaults['global_tcl_path'] + '/' + name
  8472. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8473. if ret_val == 'fail':
  8474. self.inform.emit('[ERROR_NOTCL] %s' %
  8475. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8476. "Try to load it from File menu.\n "
  8477. "Attempting to create a FlatCAM CNCJob Object from "
  8478. "G-Code file failed during processing"))
  8479. return "fail"
  8480. # Register recent file
  8481. self.app.file_opened.emit("cncjob", filename)
  8482. # appGUI feedback
  8483. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8484. def open_hpgl2(self, filename, outname=None):
  8485. """
  8486. Opens a HPGL2 file, parses it and creates a new object for
  8487. it in the program. Thread-safe.
  8488. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8489. :param filename: HPGL2 file filename
  8490. :return: None
  8491. """
  8492. filename = filename
  8493. # How the object should be initialized
  8494. def obj_init(geo_obj, app_obj):
  8495. assert isinstance(geo_obj, GeometryObject), \
  8496. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8497. # Opening the file happens here
  8498. obj = HPGL2(self.app)
  8499. try:
  8500. HPGL2.parse_file(obj, filename)
  8501. except IOError:
  8502. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8503. return "fail"
  8504. except ParseError as err:
  8505. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8506. app_obj.log.error(str(err))
  8507. return "fail"
  8508. except Exception as e:
  8509. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8510. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8511. msg += traceback.format_exc()
  8512. app_obj.inform.emit(msg)
  8513. return "fail"
  8514. geo_obj.multigeo = True
  8515. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8516. geo_obj.tools = deepcopy(obj.tools)
  8517. geo_obj.source_file = deepcopy(obj.source_file)
  8518. del obj
  8519. if not geo_obj.solid_geometry:
  8520. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8521. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8522. return "fail"
  8523. self.app.log.debug("open_hpgl2()")
  8524. with self.app.proc_container.new(_("Opening ...")):
  8525. # Object name
  8526. name = outname or filename.split('/')[-1].split('\\')[-1]
  8527. # # ## Object creation # ##
  8528. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8529. if ret == 'fail':
  8530. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed. Probable not a HPGL2 file.'))
  8531. return 'fail'
  8532. # Register recent file
  8533. self.app.file_opened.emit("geometry", filename)
  8534. # appGUI feedback
  8535. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8536. def open_script(self, filename, outname=None, silent=False):
  8537. """
  8538. Opens a Script file, parses it and creates a new object for
  8539. it in the program. Thread-safe.
  8540. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8541. :param filename: Script file filename
  8542. :param silent: If True there will be no messages printed to StatusBar
  8543. :return: None
  8544. """
  8545. def obj_init(script_obj, app_obj):
  8546. assert isinstance(script_obj, ScriptObject), \
  8547. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8548. if silent is False:
  8549. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8550. try:
  8551. script_obj.parse_file(filename)
  8552. except IOError:
  8553. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8554. return "fail"
  8555. except ParseError as err:
  8556. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8557. app_obj.log.error(str(err))
  8558. return "fail"
  8559. except Exception as e:
  8560. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8561. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8562. msg += traceback.format_exc()
  8563. app_obj.inform.emit(msg)
  8564. return "fail"
  8565. self.app.log.debug("open_script()")
  8566. with self.app.proc_container.new(_("Opening ...")):
  8567. # Object name
  8568. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8569. # Object creation
  8570. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8571. if ret_val == 'fail':
  8572. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8573. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8574. if ret_val == 'fail':
  8575. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8576. return 'fail'
  8577. # Register recent file
  8578. self.app.file_opened.emit("script", filename)
  8579. # appGUI feedback
  8580. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8581. def open_config_file(self, filename, run_from_arg=None):
  8582. """
  8583. Loads a config file from the specified file.
  8584. :param filename: Name of the file from which to load.
  8585. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8586. :return: None
  8587. """
  8588. self.app.log.debug("Opening config file: " + filename)
  8589. if run_from_arg:
  8590. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8591. "Canvas initialization finished in"),
  8592. '%.2f' % self.app.used_time,
  8593. _("Opening FlatCAM Config file.")),
  8594. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8595. color=QtGui.QColor("gray"))
  8596. # # add the tab if it was closed
  8597. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8598. # # first clear previous text in text editor (if any)
  8599. # self.ui.text_editor_tab.code_editor.clear()
  8600. #
  8601. # # Switch plot_area to CNCJob tab
  8602. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8603. # close the Code editor if already open
  8604. if self.app.toggle_codeeditor:
  8605. self.app.on_toggle_code_editor()
  8606. self.app.on_toggle_code_editor()
  8607. try:
  8608. if filename:
  8609. f = QtCore.QFile(filename)
  8610. if f.open(QtCore.QIODevice.ReadOnly):
  8611. stream = QtCore.QTextStream(f)
  8612. code_edited = stream.readAll()
  8613. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8614. f.close()
  8615. except IOError:
  8616. self.app.log.error("Failed to open config file: %s" % filename)
  8617. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8618. return
  8619. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8620. """
  8621. Loads a project from the specified file.
  8622. 1) Loads and parses file
  8623. 2) Registers the file as recently opened.
  8624. 3) Calls on_file_new()
  8625. 4) Updates options
  8626. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8627. 6) Calls plot_all() if plot=True
  8628. :param filename: Name of the file from which to load.
  8629. :param run_from_arg: True if run for arguments
  8630. :param plot: If True plot all objects in the project
  8631. :param cli: Run from command line
  8632. :param from_tcl: True if run from Tcl Sehll
  8633. :return: None
  8634. """
  8635. self.app.log.debug("Opening project: " + filename)
  8636. # block autosaving while a project is loaded
  8637. self.app.block_autosave = True
  8638. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8639. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8640. if cli is None:
  8641. self.app.ui.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8642. if run_from_arg:
  8643. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8644. "Canvas initialization finished in"),
  8645. '%.2f' % self.app.used_time,
  8646. _("Opening FlatCAM Project file.")),
  8647. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8648. color=QtGui.QColor("gray"))
  8649. # Open and parse an uncompressed Project file
  8650. try:
  8651. f = open(filename, 'r')
  8652. except IOError:
  8653. if from_tcl:
  8654. name = filename.split('/')[-1].split('\\')[-1]
  8655. filename = self.defaults['global_tcl_path'] + '/' + name
  8656. try:
  8657. f = open(filename, 'r')
  8658. except IOError:
  8659. self.app.log.error("Failed to open project file: %s" % filename)
  8660. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8661. return
  8662. else:
  8663. self.app.log.error("Failed to open project file: %s" % filename)
  8664. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8665. return
  8666. try:
  8667. d = json.load(f, object_hook=dict2obj)
  8668. except Exception as e:
  8669. self.app.log.error(
  8670. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8671. (filename, str(e)))
  8672. f.close()
  8673. # Open and parse a compressed Project file
  8674. try:
  8675. with lzma.open(filename) as f:
  8676. file_content = f.read().decode('utf-8')
  8677. d = json.loads(file_content, object_hook=dict2obj)
  8678. except Exception as e:
  8679. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8680. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8681. return
  8682. # Clear the current project
  8683. # # NOT THREAD SAFE # ##
  8684. if run_from_arg is True:
  8685. pass
  8686. elif cli is True:
  8687. self.app.delete_selection_shape()
  8688. else:
  8689. self.on_file_new()
  8690. # Project options
  8691. self.app.options.update(d['options'])
  8692. self.app.project_filename = filename
  8693. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8694. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8695. if cli is None:
  8696. self.app.set_screen_units(self.app.options["units"])
  8697. # Re create objects
  8698. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8699. for obj in d['objs']:
  8700. def obj_init(obj_inst, app_inst):
  8701. try:
  8702. obj_inst.from_dict(obj)
  8703. except Exception as erro:
  8704. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8705. return 'fail'
  8706. self.app.log.debug(
  8707. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8708. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8709. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8710. if cli is None:
  8711. self.app.ui.set_ui_title(name="{} {}: {}".format(
  8712. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8713. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8714. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8715. self.app.should_we_save = False
  8716. self.app.file_opened.emit("project", filename)
  8717. # restore autosaving after a project was loaded
  8718. self.app.block_autosave = False
  8719. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8720. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8721. if cli is None:
  8722. self.app.ui.set_ui_title(name=self.app.project_filename)
  8723. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8724. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8725. """
  8726. Saves the current project to the specified file.
  8727. :param filename: Name of the file in which to save.
  8728. :type filename: str
  8729. :param quit_action: if the project saving will be followed by an app quit; boolean
  8730. :param silent: if True will not display status messages
  8731. :param from_tcl True is run from Tcl Shell
  8732. :return: None
  8733. """
  8734. self.app.log.debug("save_project()")
  8735. self.app.save_in_progress = True
  8736. if from_tcl:
  8737. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8738. with self.app.proc_container.new(_("Saving Project ...")):
  8739. # Capture the latest changes
  8740. # Current object
  8741. try:
  8742. current_object = self.app.collection.get_active()
  8743. if current_object:
  8744. current_object.read_form()
  8745. except Exception as e:
  8746. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8747. # Serialize the whole project
  8748. d = {
  8749. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8750. "options": self.app.options,
  8751. "version": self.app.version
  8752. }
  8753. if self.defaults["global_save_compressed"] is True:
  8754. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8755. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8756. # # Write
  8757. f.write(g)
  8758. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8759. else:
  8760. # Open file
  8761. try:
  8762. f = open(filename, 'w')
  8763. except IOError:
  8764. self.app.log.error("Failed to open file for saving: %s", filename)
  8765. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8766. return
  8767. # Write
  8768. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8769. f.close()
  8770. # verification of the saved project
  8771. # Open and parse
  8772. try:
  8773. saved_f = open(filename, 'r')
  8774. except IOError:
  8775. if silent is False:
  8776. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8777. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8778. return
  8779. try:
  8780. saved_d = json.load(saved_f, object_hook=dict2obj)
  8781. except Exception:
  8782. if silent is False:
  8783. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8784. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8785. f.close()
  8786. return
  8787. saved_f.close()
  8788. if silent is False:
  8789. if 'version' in saved_d:
  8790. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8791. else:
  8792. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8793. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8794. tb_settings = QSettings("Open Source", "FlatCAM")
  8795. lock_state = self.app.ui.lock_action.isChecked()
  8796. tb_settings.setValue('toolbar_lock', lock_state)
  8797. # This will write the setting to the platform specific storage.
  8798. del tb_settings
  8799. # if quit:
  8800. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8801. # t.start()
  8802. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8803. def save_source_file(self, obj_name, filename):
  8804. """
  8805. Exports a FlatCAM Object to an Gerber/Excellon file.
  8806. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8807. :param filename: Path to the Gerber file to save to.
  8808. :return:
  8809. """
  8810. if filename is None:
  8811. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8812. is not None else self.defaults["global_last_folder"]
  8813. self.app.log.debug("save source file()")
  8814. obj = self.app.collection.get_by_name(obj_name)
  8815. file_string = StringIO(obj.source_file)
  8816. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8817. if file_string.getvalue() == '':
  8818. self.inform.emit('[ERROR_NOTCL] %s' %
  8819. _("Save cancelled because source file is empty. Try to export the file."))
  8820. return 'fail'
  8821. try:
  8822. with open(filename, 'w') as file:
  8823. file.writelines('G04*\n')
  8824. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8825. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8826. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8827. file.writelines('G04 Created on : %s*\n' % time_string)
  8828. for line in file_string:
  8829. file.writelines(line)
  8830. except PermissionError:
  8831. self.inform.emit('[WARNING] %s' %
  8832. _("Permission denied, saving not possible.\n"
  8833. "Most likely another app is holding the file open and not accessible."))
  8834. return 'fail'
  8835. def on_file_savedefaults(self):
  8836. """
  8837. Callback for menu item File->Save Defaults. Saves application default options
  8838. ``self.defaults`` to current_defaults.FlatConfig.
  8839. :return: None
  8840. """
  8841. self.app.preferencesUiManager.save_defaults()
  8842. # end of file