app_Main.py 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134
  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 io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from appDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from appObjects.ObjectCollection import *
  50. from appObjects.FlatCAMObj import FlatCAMObj
  51. from appObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from appParsers.ParseExcellon import Excellon
  54. from appParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM appGUI
  57. from appGUI.PlotCanvas import *
  58. from appGUI.PlotCanvasLegacy import *
  59. from appGUI.MainGUI import *
  60. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from appPreProcessor import load_preprocessors
  63. # FlatCAM appEditors
  64. from appEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from appEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from appEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from appEditors.FlatCAMTextEditor import TextEditor
  68. from appParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from appProcess import *
  71. from appWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from appTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import appTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = "Unstable Version"
  136. # version = 8.994
  137. version_date = "2020/07/05"
  138. beta = True
  139. engine = '3D'
  140. # current date now
  141. date = str(datetime.today()).rpartition('.')[0]
  142. date = ''.join(c for c in date if c not in ':-')
  143. date = date.replace(' ', '_')
  144. # ###############################################################################################################
  145. # ############################################ URLS's ###########################################################
  146. # ###############################################################################################################
  147. # URL for update checks and statistics
  148. version_url = "http://flatcam.org/version"
  149. # App URL
  150. app_url = "http://flatcam.org"
  151. # Manual URL
  152. manual_url = "http://flatcam.org/manual/index.html"
  153. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  154. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  155. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  156. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  157. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  158. # this variable will hold the project status
  159. # if True it will mean that the project was modified and not saved
  160. should_we_save = False
  161. # flag is True if saving action has been triggered
  162. save_in_progress = False
  163. # ###############################################################################################################
  164. # ####################################### APP Signals ######################################################
  165. # ###############################################################################################################
  166. # Inform the user
  167. # Handled by: App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. # Handled by: App.info_shell() --> Print on the shell
  170. inform_shell = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. # Emitted when a new object has been added or deleted from/to the collection
  188. object_status_changed = QtCore.pyqtSignal(object, str, str)
  189. message = QtCore.pyqtSignal(str, str, str)
  190. # Emmited when shell command is finished(one command only)
  191. shell_command_finished = QtCore.pyqtSignal(object)
  192. # Emitted when multiprocess pool has been recreated
  193. pool_recreated = QtCore.pyqtSignal(object)
  194. # Emitted when an unhandled exception happens
  195. # in the worker task.
  196. thread_exception = QtCore.pyqtSignal(object)
  197. # used to signal that there are arguments for the app
  198. args_at_startup = QtCore.pyqtSignal(list)
  199. # a reusable signal to replot a list of objects
  200. # should be disconnected after use so it can be reused
  201. replot_signal = pyqtSignal(list)
  202. # signal emitted when jumping
  203. jump_signal = pyqtSignal(tuple)
  204. # signal emitted when jumping
  205. locate_signal = pyqtSignal(tuple, str)
  206. # close app signal
  207. close_app_signal = pyqtSignal()
  208. # will perform the cleanup operation after a Graceful Exit
  209. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  210. # graphic residues behind
  211. cleanup = pyqtSignal()
  212. def __init__(self, user_defaults=True):
  213. """
  214. Starts the application.
  215. :return: app
  216. :rtype: App
  217. """
  218. super().__init__()
  219. App.log.info("FlatCAM Starting...")
  220. # ############################################################################################################
  221. # ################# Setup the listening thread for another instance launching with args ######################
  222. # ############################################################################################################
  223. if sys.platform == 'win32' or sys.platform == 'linux':
  224. # make sure the thread is stored by using a self. otherwise it's garbage collected
  225. self.listen_th = QtCore.QThread()
  226. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  227. self.new_launch = ArgsThread()
  228. self.new_launch.open_signal[list].connect(self.on_startup_args)
  229. self.new_launch.moveToThread(self.listen_th)
  230. self.new_launch.start.emit()
  231. # ############################################################################################################
  232. # ########################################## OS-specific #####################################################
  233. # ############################################################################################################
  234. portable = False
  235. # Folder for user settings.
  236. if sys.platform == 'win32':
  237. if platform.architecture()[0] == '32bit':
  238. App.log.debug("Win32!")
  239. else:
  240. App.log.debug("Win64!")
  241. # #######################################################################################################
  242. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  243. # #######################################################################################################
  244. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  245. try:
  246. with open(config_file, 'r'):
  247. pass
  248. except FileNotFoundError:
  249. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r') as f:
  252. try:
  253. for line in f:
  254. param = str(line).replace('\n', '').rpartition('=')
  255. if param[0] == 'portable':
  256. try:
  257. portable = eval(param[2])
  258. except NameError:
  259. portable = False
  260. if param[0] == 'headless':
  261. if param[2].lower() == 'true':
  262. self.cmd_line_headless = 1
  263. else:
  264. self.cmd_line_headless = None
  265. except Exception as e:
  266. log.debug('App.__init__() -->%s' % str(e))
  267. return
  268. except FileNotFoundError as e:
  269. log.debug(str(e))
  270. pass
  271. if portable is False:
  272. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  273. else:
  274. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  275. self.os = 'windows'
  276. else: # Linux/Unix/MacOS
  277. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  278. self.os = 'unix'
  279. # ############################################################################################################
  280. # ################################# Setup folders and files ##################################################
  281. # ############################################################################################################
  282. if not os.path.exists(self.data_path):
  283. os.makedirs(self.data_path)
  284. App.log.debug('Created data folder: ' + self.data_path)
  285. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  286. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  287. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  288. if not os.path.exists(self.preprocessorpaths):
  289. os.makedirs(self.preprocessorpaths)
  290. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  291. # create geo_tools_db.FlatDB file if there is none
  292. try:
  293. f = open(self.data_path + '/geo_tools_db.FlatDB')
  294. f.close()
  295. except IOError:
  296. App.log.debug('Creating empty geo_tool_db.FlatDB')
  297. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  298. json.dump({}, f)
  299. f.close()
  300. # create current_defaults.FlatConfig file if there is none
  301. try:
  302. f = open(self.data_path + '/current_defaults.FlatConfig')
  303. f.close()
  304. except IOError:
  305. App.log.debug('Creating empty current_defaults.FlatConfig')
  306. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  307. json.dump({}, f)
  308. f.close()
  309. # the factory defaults are written only once at the first launch of the application after installation
  310. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  311. # create a recent files json file if there is none
  312. try:
  313. f = open(self.data_path + '/recent.json')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty recent.json')
  317. f = open(self.data_path + '/recent.json', 'w')
  318. json.dump([], f)
  319. f.close()
  320. # create a recent projects json file if there is none
  321. try:
  322. fp = open(self.data_path + '/recent_projects.json')
  323. fp.close()
  324. except IOError:
  325. App.log.debug('Creating empty recent_projects.json')
  326. fp = open(self.data_path + '/recent_projects.json', 'w')
  327. json.dump([], fp)
  328. fp.close()
  329. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  330. # This will fail under cx_freeze ...
  331. self.app_home = os.path.dirname(os.path.realpath(__file__))
  332. log.debug("Application path is " + self.app_home)
  333. log.debug("Started in " + os.getcwd())
  334. # cx_freeze workaround
  335. if os.path.isfile(self.app_home):
  336. self.app_home = os.path.dirname(self.app_home)
  337. os.chdir(self.app_home)
  338. # ############################################################################################################
  339. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  340. # ############################################################################################################
  341. self.defaults = FlatCAMDefaults()
  342. self.defaults["root_folder_path"] = self.app_home
  343. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  344. if user_defaults:
  345. self.defaults.load(filename=current_defaults_path)
  346. if self.defaults['units'] == 'MM':
  347. self.decimals = int(self.defaults['decimals_metric'])
  348. else:
  349. self.decimals = int(self.defaults['decimals_inch'])
  350. if self.defaults["global_gray_icons"] is False:
  351. self.resource_location = 'assets/resources'
  352. else:
  353. self.resource_location = 'assets/resources/dark_resources'
  354. self.current_units = self.defaults['units']
  355. # ###########################################################################################################
  356. # #################################### SETUP OBJECT CLASSES #################################################
  357. # ###########################################################################################################
  358. self.setup_obj_classes()
  359. # ###########################################################################################################
  360. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  361. # ###########################################################################################################
  362. self.pool = Pool()
  363. # ###########################################################################################################
  364. # ###################################### Clear GUI Settings - once at first start ###########################
  365. # ###########################################################################################################
  366. if self.defaults["first_run"] is True:
  367. # on first run clear the previous QSettings, therefore clearing the GUI settings
  368. qsettings = QSettings("Open Source", "FlatCAM")
  369. for key in qsettings.allKeys():
  370. qsettings.remove(key)
  371. # This will write the setting to the platform specific storage.
  372. del qsettings
  373. # ###########################################################################################################
  374. # ###################################### Setting the Splash Screen ##########################################
  375. # ###########################################################################################################
  376. splash_settings = QSettings("Open Source", "FlatCAM")
  377. if splash_settings.contains("splash_screen"):
  378. show_splash = splash_settings.value("splash_screen")
  379. else:
  380. splash_settings.setValue('splash_screen', 1)
  381. # This will write the setting to the platform specific storage.
  382. del splash_settings
  383. show_splash = 1
  384. if show_splash and self.cmd_line_headless != 1:
  385. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  386. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  387. # self.splash.setMask(splash_pix.mask())
  388. # move splashscreen to the current monitor
  389. desktop = QtWidgets.QApplication.desktop()
  390. screen = desktop.screenNumber(QtGui.QCursor.pos())
  391. current_screen_center = desktop.availableGeometry(screen).center()
  392. self.splash.move(current_screen_center - self.splash.rect().center())
  393. self.splash.show()
  394. self.splash.showMessage(_("FlatCAM is initializing ..."),
  395. alignment=Qt.AlignBottom | Qt.AlignLeft,
  396. color=QtGui.QColor("gray"))
  397. else:
  398. show_splash = 0
  399. # ###########################################################################################################
  400. # ######################################### Initialize GUI ##################################################
  401. # ###########################################################################################################
  402. # FlatCAM colors used in plotting
  403. self.FC_light_green = '#BBF268BF'
  404. self.FC_dark_green = '#006E20BF'
  405. self.FC_light_blue = '#a5a5ffbf'
  406. self.FC_dark_blue = '#0000ffbf'
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. # update the defaults dict with the setting in QSetting
  420. self.defaults['global_theme'] = theme
  421. self.ui = MainGUI(self)
  422. # set FlatCAM units in the Status bar
  423. self.set_screen_units(self.defaults['units'])
  424. # ###########################################################################################################
  425. # ########################################### AUTOSAVE SETUP ################################################
  426. # ###########################################################################################################
  427. self.block_autosave = False
  428. self.autosave_timer = QtCore.QTimer(self)
  429. self.save_project_auto_update()
  430. self.autosave_timer.timeout.connect(self.save_project_auto)
  431. # ###########################################################################################################
  432. # #################################### LOAD PREPROCESSORS ###################################################
  433. # ###########################################################################################################
  434. # ----------------------------------------- WARNING --------------------------------------------------------
  435. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  436. # That's because the number of preprocessors can vary and here the comboboxes are populated
  437. # -----------------------------------------------------------------------------------------------------------
  438. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  439. # the preprocessor file
  440. self.preprocessors = load_preprocessors(self)
  441. # make sure that always the 'default' preprocessor is the first item in the dictionary
  442. if 'default' in self.preprocessors.keys():
  443. new_ppp_dict = {}
  444. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  445. default_pp = self.preprocessors.pop('default')
  446. new_ppp_dict['default'] = default_pp
  447. # then add the rest of the keys
  448. for name, val_class in self.preprocessors.items():
  449. new_ppp_dict[name] = val_class
  450. # and now put back the ordered dict with 'default' key first
  451. self.preprocessors = new_ppp_dict
  452. for name in list(self.preprocessors.keys()):
  453. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  454. if name.partition('_')[0] == 'Paste':
  455. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  456. continue
  457. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  458. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  459. if name == 'hpgl':
  460. continue
  461. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  462. # ###########################################################################################################
  463. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  464. # ###########################################################################################################
  465. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  466. inform=self.inform)
  467. self.preferencesUiManager.defaults_write_form()
  468. # When the self.defaults dictionary changes will update the Preferences GUI forms
  469. self.defaults.set_change_callback(self.on_defaults_dict_change)
  470. # ###########################################################################################################
  471. # ##################################### FIRST RUN SECTION ###################################################
  472. # ################################ It's done only once after install #####################################
  473. # ###########################################################################################################
  474. if self.defaults["first_run"] is True:
  475. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  476. initial_lay = 'minimal'
  477. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  478. # Set the combobox in Preferences to the current layout
  479. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  480. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  481. # after the first run, this object should be False
  482. self.defaults["first_run"] = False
  483. self.preferencesUiManager.save_defaults(silent=True)
  484. # ###########################################################################################################
  485. # ############################################ Data #########################################################
  486. # ###########################################################################################################
  487. self.recent = []
  488. self.recent_projects = []
  489. self.clipboard = QtWidgets.QApplication.clipboard()
  490. self.project_filename = None
  491. self.toggle_units_ignore = False
  492. self.main_thread = QtWidgets.QApplication.instance().thread()
  493. # ###########################################################################################################
  494. # ########################################## LOAD LANGUAGES ################################################
  495. # ###########################################################################################################
  496. self.languages = fcTranslate.load_languages()
  497. for name in sorted(self.languages.values()):
  498. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  499. # ###########################################################################################################
  500. # ####################################### APPLY APP LANGUAGE ################################################
  501. # ###########################################################################################################
  502. ret_val = fcTranslate.apply_language('strings')
  503. if ret_val == "no language":
  504. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  505. log.debug("Could not find the Language files. The App strings are missing.")
  506. else:
  507. # make the current language the current selection on the language combobox
  508. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  509. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  510. # ###########################################################################################################
  511. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  512. # ###########################################################################################################
  513. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  514. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  515. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  516. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  517. self.defaults.propagate_defaults()
  518. # ###########################################################################################################
  519. # ######################################## UPDATE THE OPTIONS ###############################################
  520. # ###########################################################################################################
  521. self.options = LoudDict()
  522. # -----------------------------------------------------------------------------------------------------------
  523. # Update the self.options from the self.defaults
  524. # The self.defaults holds the application defaults while the self.options holds the object defaults
  525. # -----------------------------------------------------------------------------------------------------------
  526. # Copy app defaults to project options
  527. for def_key, def_val in self.defaults.items():
  528. self.options[def_key] = deepcopy(def_val)
  529. self.preferencesUiManager.show_preferences_gui()
  530. # ### End of Data ####
  531. # ###########################################################################################################
  532. # #################################### SETUP OBJECT COLLECTION ##############################################
  533. # ###########################################################################################################
  534. self.collection = ObjectCollection(app=self)
  535. self.ui.project_tab_layout.addWidget(self.collection.view)
  536. self.app_obj = AppObject(app=self)
  537. # ### Adjust tabs width ## ##
  538. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  539. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  540. self.collection.view.setMinimumWidth(290)
  541. self.log.debug("Finished creating Object Collection.")
  542. # ###########################################################################################################
  543. # ######################################## SETUP Plot Area ##################################################
  544. # ###########################################################################################################
  545. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  546. if self.defaults["global_graphic_engine"] == '3D':
  547. self.is_legacy = False
  548. else:
  549. self.is_legacy = True
  550. # Event signals disconnect id holders
  551. self.mp = None
  552. self.mm = None
  553. self.mr = None
  554. self.mdc = None
  555. self.mp_zc = None
  556. self.kp = None
  557. # Matplotlib axis
  558. self.axes = None
  559. if show_splash:
  560. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  561. "Canvas initialization started."),
  562. alignment=Qt.AlignBottom | Qt.AlignLeft,
  563. color=QtGui.QColor("gray"))
  564. start_plot_time = time.time() # debug
  565. self.plotcanvas = None
  566. self.app_cursor = None
  567. self.hover_shapes = None
  568. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  569. # setup the PlotCanvas
  570. self.on_plotcanvas_setup()
  571. end_plot_time = time.time()
  572. self.used_time = end_plot_time - start_plot_time
  573. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  574. if show_splash:
  575. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started.\n"
  577. "Canvas initialization finished in"), '%.2f' % self.used_time),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. self.ui.splitter.setStretchFactor(1, 2)
  581. # ###########################################################################################################
  582. # ############################################### SYS TRAY ##################################################
  583. # ###########################################################################################################
  584. if self.defaults["global_systray_icon"]:
  585. self.parent_w = QtWidgets.QWidget()
  586. if self.cmd_line_headless == 1:
  587. self.trayIcon = FlatCAMSystemTray(app=self,
  588. icon=QtGui.QIcon(self.resource_location +
  589. '/flatcam_icon32_green.png'),
  590. headless=True,
  591. parent=self.parent_w)
  592. else:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. parent=self.parent_w)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ###########################################
  608. # ###########################################################################################################
  609. self.activity_view = FlatCAMActivityView(app=self)
  610. self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  612. # ###########################################################################################################
  613. # ############################################# Signal handling #############################################
  614. # ###########################################################################################################
  615. # ########################################## Custom signals ################################################
  616. # signal for displaying messages in status bar
  617. self.inform[str].connect(self.info)
  618. self.inform[str, bool].connect(self.info)
  619. # signal for displaying messages in the shell
  620. self.inform_shell.connect(self.info_shell)
  621. # signal to be called when the app is quiting
  622. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  623. self.message.connect(lambda: message_dialog(parent=self.ui))
  624. # self.progress.connect(self.set_progress_bar)
  625. # signals emitted when file state change
  626. self.file_opened.connect(self.register_recent)
  627. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  628. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  629. # ########################################## Standard signals ###############################################
  630. # ### Menu
  631. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  632. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  633. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  634. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  635. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  636. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  637. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  638. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  639. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  640. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  641. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  642. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  643. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  644. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  645. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  646. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  647. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  648. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  649. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  650. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  651. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  652. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  653. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  654. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  655. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  656. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  657. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  658. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  659. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  660. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  661. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  662. self.ui.menufile_exit.triggered.connect(self.final_save)
  663. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  664. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  665. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  666. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  667. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  668. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  669. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  670. self.ui.menueditdelete.triggered.connect(self.on_delete)
  671. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  672. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  673. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  674. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  675. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  676. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  677. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  678. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  679. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  680. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  681. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  682. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  683. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  684. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  685. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  686. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  687. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  688. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  689. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  690. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  691. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  692. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  693. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  694. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  695. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  696. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  697. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  698. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  699. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  700. self.ui.menuview_replot.triggered.connect(self.plot_all)
  701. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  702. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  703. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  704. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  705. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  706. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  707. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  708. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  709. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  710. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  711. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  712. self.ui.menuhelp_about.triggered.connect(self.on_about)
  713. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  729. # ToolBar signals
  730. self.connect_toolbar_signals()
  731. # Notebook and Plot Tab Area signals
  732. # make the right click on the notebook tab and plot tab area tab raise a menu
  733. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  734. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.on_tab_setup_context_menu()
  736. # activate initial state
  737. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  738. # Context Menu
  739. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  740. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  741. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  742. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  743. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  744. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  745. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  746. self.ui.clearplot.triggered.connect(self.clear_plots)
  747. self.ui.replot.triggered.connect(self.plot_all)
  748. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  749. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  750. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  751. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  752. self.ui.popmenu_move.triggered.connect(self.obj_move)
  753. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  754. # Project Context Menu -> Color Setting
  755. for act in self.ui.menuprojectcolor.actions():
  756. act.triggered.connect(self.on_set_color_action_triggered)
  757. # ###########################################################################################################
  758. # #################################### GUI PREFERENCES SIGNALS ##############################################
  759. # ###########################################################################################################
  760. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  761. lambda: self.on_toggle_units(no_pref=False))
  762. # ##################################### Workspace Setting Signals ###########################################
  763. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  764. self.on_workspace_modified)
  765. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  766. self.on_workspace_modified
  767. )
  768. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  769. # ###########################################################################################################
  770. # ######################################## GUI SETTINGS SIGNALS #############################################
  771. # ###########################################################################################################
  772. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  773. # ######################################## Tools related signals ############################################
  774. # portability changed signal
  775. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  776. # Object list
  777. self.object_status_changed.connect(self.collection.on_collection_updated)
  778. # when there are arguments at application startup this get launched
  779. self.args_at_startup[list].connect(self.on_startup_args)
  780. # ###########################################################################################################
  781. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  782. # ###########################################################################################################
  783. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  784. lambda: self.restore_extensions(ext_type='excellon'))
  785. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  786. lambda: self.restore_extensions(ext_type='gcode'))
  787. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  788. lambda: self.restore_extensions(ext_type='gerber'))
  789. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  790. lambda: self.delete_all_extensions(ext_type='excellon'))
  791. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  792. lambda: self.delete_all_extensions(ext_type='gcode'))
  793. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  794. lambda: self.delete_all_extensions(ext_type='gerber'))
  795. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  796. lambda: self.add_extension(ext_type='excellon'))
  797. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  798. lambda: self.add_extension(ext_type='gcode'))
  799. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  800. lambda: self.add_extension(ext_type='gerber'))
  801. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  802. lambda: self.del_extension(ext_type='excellon'))
  803. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  804. lambda: self.del_extension(ext_type='gcode'))
  805. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  806. lambda: self.del_extension(ext_type='gerber'))
  807. # connect the 'Apply' buttons from the Preferences/File Associations
  808. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  809. lambda: self.on_register_files(obj_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  811. lambda: self.on_register_files(obj_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  813. lambda: self.on_register_files(obj_type='gerber'))
  814. # ###########################################################################################################
  815. # ########################################### KEYWORDS SIGNALS ##############################################
  816. # ###########################################################################################################
  817. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='keyword'))
  819. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='keyword'))
  821. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  822. lambda: self.add_extension(ext_type='keyword'))
  823. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  824. lambda: self.del_extension(ext_type='keyword'))
  825. # ###########################################################################################################
  826. # ########################################### GUI SIGNALS ###################################################
  827. # ###########################################################################################################
  828. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  829. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  830. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  831. # ###########################################################################################################
  832. # ####################################### VARIOUS SIGNALS ###################################################
  833. # ###########################################################################################################
  834. # connect the abort_all_tasks related slots to the related signals
  835. self.proc_container.idle_flag.connect(self.app_is_idle)
  836. # signal emitted when a tab is closed in the Plot Area
  837. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  838. # signal to close the application
  839. self.close_app_signal.connect(self.kill_app)
  840. # ################################# FINISHED CONNECTING SIGNALS #############################################
  841. # ###########################################################################################################
  842. # ###########################################################################################################
  843. # ###########################################################################################################
  844. self.log.debug("Finished connecting Signals.")
  845. # ###########################################################################################################
  846. # ########################################## Other setups ###################################################
  847. # ###########################################################################################################
  848. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  849. # depending on from where those tools are called different actions can be done
  850. self.call_source = 'app'
  851. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  852. self.tool_tab_locked = False
  853. # decide if to show or hide the Notebook side of the screen at startup
  854. if self.defaults["global_project_at_startup"] is True:
  855. self.ui.splitter.setSizes([1, 1])
  856. else:
  857. self.ui.splitter.setSizes([0, 1])
  858. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  859. self.setup_component_editor()
  860. # ###########################################################################################################
  861. # ####################################### Auto-complete KEYWORDS ############################################
  862. # ###########################################################################################################
  863. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  864. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  865. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  866. 'export_exc',
  867. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  868. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  869. 'interiors', 'isolate', 'join_excellon',
  870. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  871. 'mirror', 'ncc',
  872. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  873. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  874. 'options', 'origin',
  875. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  876. 'save', 'save_project',
  877. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  878. 'skew', 'subtract_poly', 'subtract_rectangle',
  879. 'version', 'write_gcode'
  880. ]
  881. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  882. 'Paste_1',
  883. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  884. 'Toolchange_manual', 'True', 'Users',
  885. 'all', 'auto', 'axis',
  886. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  887. 'contour', 'default',
  888. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  889. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  890. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  891. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  892. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  893. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  894. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  895. 'spacing_columns',
  896. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  897. 'toolchange_xy', 'toolchangez', 'travelz',
  898. 'tooldia', 'use_threads', 'value',
  899. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  900. ]
  901. self.tcl_keywords = [
  902. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  903. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  904. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  905. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  906. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  907. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  908. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  909. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  910. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  911. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  912. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  913. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  914. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  915. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  916. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  917. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  918. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  919. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  920. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  921. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  922. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  923. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  924. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  925. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  926. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  927. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  928. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  929. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  930. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  931. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  932. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  933. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  934. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  935. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  936. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  937. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  938. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  939. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  940. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  941. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  942. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  943. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  944. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  945. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  946. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  947. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  948. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  949. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  950. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  951. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  952. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  953. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  954. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  955. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  956. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  957. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  958. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  959. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  960. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  961. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  962. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  963. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  964. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  965. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  966. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  967. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  968. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  969. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  970. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  971. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  972. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  973. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  974. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  975. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  976. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  977. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  978. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  979. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  980. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  981. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  982. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  983. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  984. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  985. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  986. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  987. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  988. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  989. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  990. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  991. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  992. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  993. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  994. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  995. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  996. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  997. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  998. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  999. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1000. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1001. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1002. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1003. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1004. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1005. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1006. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1007. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1008. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1009. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1010. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1011. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1012. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1013. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1014. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1015. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1016. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1017. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1018. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1019. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1020. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1021. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1022. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1023. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1024. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1025. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1026. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1027. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1028. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1029. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1030. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1031. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1032. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1033. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1034. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1035. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1036. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1037. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1038. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1039. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1040. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1041. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1042. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1043. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1044. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1045. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1046. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1047. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1048. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1049. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1050. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1051. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1052. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1053. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1054. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1055. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1056. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1057. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1058. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1059. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1060. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1061. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1062. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1063. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1064. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1065. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1066. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1067. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1068. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1069. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1070. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1071. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1072. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1073. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1074. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1075. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1076. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1077. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1078. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1079. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1080. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1081. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1082. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1083. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1084. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1085. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1086. ]
  1087. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1088. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1089. # ###########################################################################################################
  1090. # ############################################## Shell SETUP ################################################
  1091. # ###########################################################################################################
  1092. self.shell = FCShell(app=self, version=self.version)
  1093. self.ui.shell_dock.setWidget(self.shell)
  1094. self.log.debug("TCL Shell has been initialized.")
  1095. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1096. if self.defaults["global_shell_at_startup"]:
  1097. self.ui.shell_dock.show()
  1098. else:
  1099. self.ui.shell_dock.hide()
  1100. # ###########################################################################################################
  1101. # ########################################## Tools and Plugins ##############################################
  1102. # ###########################################################################################################
  1103. self.dblsidedtool = None
  1104. self.distance_tool = None
  1105. self.distance_min_tool = None
  1106. self.panelize_tool = None
  1107. self.film_tool = None
  1108. self.paste_tool = None
  1109. self.calculator_tool = None
  1110. self.rules_tool = None
  1111. self.sub_tool = None
  1112. self.move_tool = None
  1113. self.cutout_tool = None
  1114. self.ncclear_tool = None
  1115. self.paint_tool = None
  1116. self.isolation_tool = None
  1117. self.optimal_tool = None
  1118. self.transform_tool = None
  1119. self.properties_tool = None
  1120. self.pdf_tool = None
  1121. self.image_tool = None
  1122. self.pcb_wizard_tool = None
  1123. self.cal_exc_tool = None
  1124. self.qrcode_tool = None
  1125. self.copper_thieving_tool = None
  1126. self.fiducial_tool = None
  1127. self.edrills_tool = None
  1128. self.align_objects_tool = None
  1129. self.punch_tool = None
  1130. self.invert_tool = None
  1131. self.corners_tool = None
  1132. self.etch_tool = None
  1133. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1134. try:
  1135. self.install_tools()
  1136. except AttributeError as e:
  1137. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1138. # ###########################################################################################################
  1139. # ############################################ SETUP RECENT ITEMS ###########################################
  1140. # ###########################################################################################################
  1141. self.setup_recent_items()
  1142. # ###########################################################################################################
  1143. # ######################################### BookMarks Manager ###############################################
  1144. # ###########################################################################################################
  1145. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1146. self.install_bookmarks()
  1147. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1148. # ###########################################################################################################
  1149. # ########################################### Tools Database ################################################
  1150. # ###########################################################################################################
  1151. self.tools_db_tab = None
  1152. # ### System Font Parsing ###
  1153. # self.f_parse = ParseFont(self)
  1154. # self.parse_system_fonts()
  1155. # ###########################################################################################################
  1156. # ######################################### Check for updates ###############################################
  1157. # ###########################################################################################################
  1158. # Separate thread (Not worker)
  1159. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1160. if (self.beta is False or self.beta is None) and \
  1161. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1162. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1163. # self.thr2 = QtCore.QThread()
  1164. self.worker_task.emit({'fcn': self.version_check,
  1165. 'params': []})
  1166. # self.thr2.start(QtCore.QThread.LowPriority)
  1167. # ###########################################################################################################
  1168. # ##################################### Register files with FlatCAM; #######################################
  1169. # ################################### It works only for Windows for now ####################################
  1170. # ###########################################################################################################
  1171. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1172. self.on_register_files()
  1173. # ###########################################################################################################
  1174. # ######################################## Variables for global usage #######################################
  1175. # ###########################################################################################################
  1176. # hold the App units
  1177. self.units = 'MM'
  1178. # coordinates for relative position display
  1179. self.rel_point1 = (0, 0)
  1180. self.rel_point2 = (0, 0)
  1181. # variable to store coordinates
  1182. self.pos = (0, 0)
  1183. self.pos_canvas = (0, 0)
  1184. self.pos_jump = (0, 0)
  1185. # variable to store mouse coordinates
  1186. self.mouse = [0, 0]
  1187. # variable to store the delta positions on cavnas
  1188. self.dx = 0
  1189. self.dy = 0
  1190. # decide if we have a double click or single click
  1191. self.doubleclick = False
  1192. # store here the is_dragging value
  1193. self.event_is_dragging = False
  1194. # variable to store if a command is active (then the var is not None) and which one it is
  1195. self.command_active = None
  1196. # variable to store the status of moving selection action
  1197. # None value means that it's not an selection action
  1198. # True value = a selection from left to right
  1199. # False value = a selection from right to left
  1200. self.selection_type = None
  1201. # List to store the objects that are currently loaded in FlatCAM
  1202. # This list is updated on each object creation or object delete
  1203. self.all_objects_list = []
  1204. self.objects_under_the_click_list = []
  1205. # List to store the objects that are selected
  1206. self.sel_objects_list = []
  1207. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1208. self.key_modifiers = None
  1209. # Variable to store the status of the code editor
  1210. self.toggle_codeeditor = False
  1211. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1212. self.click_noproject = False
  1213. self.cursor = None
  1214. # Variable to store the GCODE that was edited
  1215. self.gcode_edited = ""
  1216. self.text_editor_tab = None
  1217. # reference for the self.ui.code_editor
  1218. self.reference_code_editor = None
  1219. self.script_code = ''
  1220. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1221. self.tools_db_changed_flag = False
  1222. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1223. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1224. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1225. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1226. 'tsm']
  1227. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1228. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1229. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1230. 'sbp', 'tap', 'xpi']
  1231. self.svg_list = ['svg']
  1232. self.dxf_list = ['dxf']
  1233. self.pdf_list = ['pdf']
  1234. self.prj_list = ['flatprj']
  1235. self.conf_list = ['flatconfig']
  1236. # last used filters
  1237. self.last_op_gerber_filter = None
  1238. self.last_op_excellon_filter = None
  1239. self.last_op_gcode_filter = None
  1240. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1241. # flag for polygons not cleared
  1242. self.poly_not_cleared = False
  1243. # VisPy visuals
  1244. self.isHovering = False
  1245. self.notHovering = True
  1246. # Window geometry
  1247. self.x_pos = None
  1248. self.y_pos = None
  1249. self.width = None
  1250. self.height = None
  1251. # when True, the app has to return from any thread
  1252. self.abort_flag = False
  1253. # set the value used in the Windows Title
  1254. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1255. # this holds a widget that is installed in the Plot Area when View Source option is used
  1256. self.source_editor_tab = None
  1257. self.pagesize = {}
  1258. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1259. # VisPy visuals
  1260. if self.is_legacy is False:
  1261. try:
  1262. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1263. except AttributeError:
  1264. self.tool_shapes = None
  1265. else:
  1266. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1267. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1268. # used in the delayed shutdown self.start_delayed_quit() method
  1269. self.save_timer = None
  1270. # ###########################################################################################################
  1271. # ################################## ADDING FlatCAM EDITORS section #########################################
  1272. # ###########################################################################################################
  1273. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1274. # at the first launch of the App , the editors will not be functional.
  1275. try:
  1276. self.geo_editor = FlatCAMGeoEditor(self)
  1277. except Exception as es:
  1278. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1279. try:
  1280. self.exc_editor = FlatCAMExcEditor(self)
  1281. except Exception as es:
  1282. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1283. try:
  1284. self.grb_editor = FlatCAMGrbEditor(self)
  1285. except Exception as es:
  1286. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1287. self.log.debug("Finished adding FlatCAM Editor's.")
  1288. self.set_ui_title(name=_("New Project - Not saved"))
  1289. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1290. current_platform = platform.architecture()[0]
  1291. if current_platform != '64bit':
  1292. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1293. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1294. # ###########################################################################################################
  1295. # ########################################### EXCLUSION AREAS ###############################################
  1296. # ###########################################################################################################
  1297. self.exc_areas = ExclusionAreas(app=self)
  1298. # ###########################################################################################################
  1299. # ##################################### Finished the CONSTRUCTOR ############################################
  1300. # ###########################################################################################################
  1301. App.log.debug("END of constructor. Releasing control.")
  1302. # ###########################################################################################################
  1303. # ########################################## SHOW GUI #######################################################
  1304. # ###########################################################################################################
  1305. # if the app is not started as headless, show it
  1306. if self.cmd_line_headless != 1:
  1307. if show_splash:
  1308. # finish the splash
  1309. self.splash.finish(self.ui)
  1310. mgui_settings = QSettings("Open Source", "FlatCAM")
  1311. if mgui_settings.contains("maximized_gui"):
  1312. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1313. if maximized_ui is True:
  1314. self.ui.showMaximized()
  1315. else:
  1316. self.ui.show()
  1317. else:
  1318. self.ui.show()
  1319. if self.defaults["global_systray_icon"]:
  1320. self.trayIcon.show()
  1321. else:
  1322. log.warning("******************* RUNNING HEADLESS *******************")
  1323. # ###########################################################################################################
  1324. # ######################################## START-UP ARGUMENTS ###############################################
  1325. # ###########################################################################################################
  1326. # test if the program was started with a script as parameter
  1327. if self.cmd_line_shellvar:
  1328. try:
  1329. cnt = 0
  1330. command_tcl = 0
  1331. for i in self.cmd_line_shellvar.split(','):
  1332. if i is not None:
  1333. # noinspection PyBroadException
  1334. try:
  1335. command_tcl = eval(i)
  1336. except Exception:
  1337. command_tcl = i
  1338. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1339. cnt += 1
  1340. # if there are Windows paths then replace the path separator with a Unix like one
  1341. if sys.platform == 'win32':
  1342. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1343. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1344. except Exception as ext:
  1345. print("ERROR: ", ext)
  1346. sys.exit(2)
  1347. if self.cmd_line_shellfile:
  1348. if self.cmd_line_headless != 1:
  1349. if self.ui.shell_dock.isHidden():
  1350. self.ui.shell_dock.show()
  1351. try:
  1352. with open(self.cmd_line_shellfile, "r") as myfile:
  1353. # if show_splash:
  1354. # self.splash.showMessage('%s: %ssec\n%s' % (
  1355. # _("Canvas initialization started.\n"
  1356. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1357. # _("Executing Tcl Script ...")),
  1358. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1359. # color=QtGui.QColor("gray"))
  1360. cmd_line_shellfile_text = myfile.read()
  1361. if self.cmd_line_headless != 1:
  1362. self.shell.exec_command(cmd_line_shellfile_text)
  1363. else:
  1364. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1365. except Exception as ext:
  1366. print("ERROR: ", ext)
  1367. sys.exit(2)
  1368. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1369. # the path/file_name must be enclosed in quotes if it contain spaces
  1370. if App.args:
  1371. self.args_at_startup.emit(App.args)
  1372. if self.defaults.old_defaults_found is True:
  1373. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1374. "Please reboot the application to update."))
  1375. self.defaults.old_defaults_found = False
  1376. # ######################################### INIT FINISHED #######################################################
  1377. # #################################################################################################################
  1378. # #################################################################################################################
  1379. # #################################################################################################################
  1380. # #################################################################################################################
  1381. # #################################################################################################################
  1382. @staticmethod
  1383. def copy_and_overwrite(from_path, to_path):
  1384. """
  1385. From here:
  1386. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1387. :param from_path: source path
  1388. :param to_path: destination path
  1389. :return: None
  1390. """
  1391. if os.path.exists(to_path):
  1392. shutil.rmtree(to_path)
  1393. try:
  1394. shutil.copytree(from_path, to_path)
  1395. except FileNotFoundError:
  1396. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1397. shutil.copytree(from_new_path, to_path)
  1398. def on_startup_args(self, args, silent=False):
  1399. """
  1400. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1401. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1402. :param args: a list containing the application args at startup
  1403. :return: None
  1404. """
  1405. if args is not None:
  1406. args_to_process = args
  1407. else:
  1408. args_to_process = App.args
  1409. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1410. for argument in args_to_process:
  1411. if '.FlatPrj'.lower() in argument.lower():
  1412. try:
  1413. project_name = str(argument)
  1414. if project_name == "":
  1415. if silent is False:
  1416. self.inform.emit(_("Cancelled."))
  1417. else:
  1418. # self.open_project(project_name)
  1419. run_from_arg = True
  1420. # self.worker_task.emit({'fcn': self.open_project,
  1421. # 'params': [project_name, run_from_arg]})
  1422. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1423. except Exception as e:
  1424. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1425. elif '.FlatConfig'.lower() in argument.lower():
  1426. try:
  1427. file_name = str(argument)
  1428. if file_name == "":
  1429. if silent is False:
  1430. self.inform.emit(_("Open Config file failed."))
  1431. else:
  1432. run_from_arg = True
  1433. # self.worker_task.emit({'fcn': self.open_config_file,
  1434. # 'params': [file_name, run_from_arg]})
  1435. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1436. except Exception as e:
  1437. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1438. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1439. try:
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Script file failed."))
  1444. else:
  1445. if silent is False:
  1446. self.on_fileopenscript(name=file_name)
  1447. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1448. self.on_filerunscript(name=file_name)
  1449. except Exception as e:
  1450. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1451. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1452. log.debug("App.on_startup_args() --> Quit event.")
  1453. sys.exit()
  1454. elif 'save'.lower() in argument.lower():
  1455. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1456. self.preferencesUiManager.save_defaults()
  1457. else:
  1458. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1459. proc_arg = argument.lower()
  1460. for ext in exc_list:
  1461. proc_ext = ext.replace(' ', '')
  1462. proc_ext = '.%s' % proc_ext
  1463. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1464. file_name = str(argument)
  1465. if file_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Open Excellon file failed."))
  1468. else:
  1469. self.on_fileopenexcellon(name=file_name, signal=None)
  1470. return
  1471. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1472. for ext in gco_list:
  1473. proc_ext = ext.replace(' ', '')
  1474. proc_ext = '.%s' % proc_ext
  1475. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1476. file_name = str(argument)
  1477. if file_name == "":
  1478. if silent is False:
  1479. self.inform.emit(_("Open GCode file failed."))
  1480. else:
  1481. self.on_fileopengcode(name=file_name, signal=None)
  1482. return
  1483. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1484. for ext in grb_list:
  1485. proc_ext = ext.replace(' ', '')
  1486. proc_ext = '.%s' % proc_ext
  1487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1488. file_name = str(argument)
  1489. if file_name == "":
  1490. if silent is False:
  1491. self.inform.emit(_("Open Gerber file failed."))
  1492. else:
  1493. self.on_fileopengerber(name=file_name, signal=None)
  1494. return
  1495. # if it reached here without already returning then the app was registered with a file that it does not
  1496. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1497. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1498. # for arg in args_to_process:
  1499. # if 'FlatCAM.exe' in arg:
  1500. # continue
  1501. # else:
  1502. # sys.exit(2)
  1503. def set_ui_title(self, name):
  1504. """
  1505. Sets the title of the main window.
  1506. :param name: String that store the project path and project name
  1507. :return: None
  1508. """
  1509. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1510. (self.version,
  1511. ('BETA' if self.beta else ''),
  1512. platform.architecture()[0],
  1513. self.engine,
  1514. name)
  1515. )
  1516. def on_app_restart(self):
  1517. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1518. # be left in the SySTray
  1519. try:
  1520. self.trayIcon.hide()
  1521. except Exception:
  1522. pass
  1523. fcTranslate.restart_program(app=self)
  1524. def clear_pool(self):
  1525. """
  1526. Clear the multiprocessing pool and calls garbage collector.
  1527. :return: None
  1528. """
  1529. self.pool.close()
  1530. self.pool = Pool()
  1531. self.pool_recreated.emit(self.pool)
  1532. gc.collect()
  1533. def install_tools(self):
  1534. """
  1535. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1536. Instantiation of the Tools classes.
  1537. The order that the tools are installed is important as they can depend on each other install position.
  1538. :return: None
  1539. """
  1540. self.distance_tool = Distance(self)
  1541. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1542. before=self.ui.menueditorigin,
  1543. separator=False)
  1544. self.distance_min_tool = DistanceMin(self)
  1545. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1546. pos=self.ui.menuedit,
  1547. before=self.ui.menueditorigin,
  1548. separator=True)
  1549. self.dblsidedtool = DblSidedTool(self)
  1550. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1551. self.cal_exc_tool = ToolCalibration(self)
  1552. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1553. before=self.dblsidedtool.menuAction,
  1554. separator=False)
  1555. self.align_objects_tool = AlignObjects(self)
  1556. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1557. self.edrills_tool = ToolExtractDrills(self)
  1558. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1559. self.panelize_tool = Panelize(self)
  1560. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1561. self.film_tool = Film(self)
  1562. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1563. self.paste_tool = SolderPaste(self)
  1564. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1565. self.calculator_tool = ToolCalculator(self)
  1566. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1567. self.sub_tool = ToolSub(self)
  1568. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1569. pos=self.ui.menutool, separator=True)
  1570. self.rules_tool = RulesCheck(self)
  1571. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1572. pos=self.ui.menutool, separator=False)
  1573. self.optimal_tool = ToolOptimal(self)
  1574. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1575. pos=self.ui.menutool, separator=True)
  1576. self.move_tool = ToolMove(self)
  1577. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1578. before=self.ui.menueditorigin, separator=True)
  1579. self.cutout_tool = CutOut(self)
  1580. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1581. before=self.sub_tool.menuAction)
  1582. self.ncclear_tool = NonCopperClear(self)
  1583. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1584. before=self.sub_tool.menuAction, separator=True)
  1585. self.paint_tool = ToolPaint(self)
  1586. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1587. before=self.sub_tool.menuAction, separator=True)
  1588. self.isolation_tool = ToolIsolation(self)
  1589. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction, separator=True)
  1591. self.copper_thieving_tool = ToolCopperThieving(self)
  1592. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1593. pos=self.ui.menutool)
  1594. self.fiducial_tool = ToolFiducials(self)
  1595. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1596. pos=self.ui.menutool)
  1597. self.qrcode_tool = QRCode(self)
  1598. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1599. pos=self.ui.menutool)
  1600. self.punch_tool = ToolPunchGerber(self)
  1601. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1602. self.invert_tool = ToolInvertGerber(self)
  1603. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1604. self.corners_tool = ToolCorners(self)
  1605. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1606. self.etch_tool = ToolEtchCompensation(self)
  1607. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1608. self.transform_tool = ToolTransform(self)
  1609. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1610. pos=self.ui.menuoptions, separator=True)
  1611. self.properties_tool = Properties(self)
  1612. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1613. pos=self.ui.menuoptions)
  1614. self.pdf_tool = ToolPDF(self)
  1615. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1616. pos=self.ui.menufileimport,
  1617. separator=True)
  1618. self.image_tool = ToolImage(self)
  1619. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1620. pos=self.ui.menufileimport,
  1621. separator=True)
  1622. self.pcb_wizard_tool = PcbWizard(self)
  1623. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1624. pos=self.ui.menufileimport)
  1625. self.log.debug("Tools are installed.")
  1626. def remove_tools(self):
  1627. """
  1628. Will remove all the actions in the Tool menu.
  1629. :return: None
  1630. """
  1631. for act in self.ui.menutool.actions():
  1632. self.ui.menutool.removeAction(act)
  1633. def init_tools(self):
  1634. """
  1635. Initialize the Tool tab in the notebook side of the central widget.
  1636. Remove the actions in the Tools menu.
  1637. Instantiate again the FlatCAM tools (plugins).
  1638. All this is required when changing the layout: standard, compact etc.
  1639. :return: None
  1640. """
  1641. log.debug("init_tools()")
  1642. # delete the data currently in the Tools Tab and the Tab itself
  1643. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1644. if widget is not None:
  1645. widget.deleteLater()
  1646. self.ui.notebook.removeTab(2)
  1647. # rebuild the Tools Tab
  1648. self.ui.tool_tab = QtWidgets.QWidget()
  1649. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1650. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1651. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1652. self.ui.tool_scroll_area = VerticalScrollArea()
  1653. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1654. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1655. # first remove all of them
  1656. self.remove_tools()
  1657. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1658. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1659. '&Command Line\tS')
  1660. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1661. # third install all of them
  1662. try:
  1663. self.install_tools()
  1664. except AttributeError:
  1665. pass
  1666. self.log.debug("Tools are initialized.")
  1667. # def parse_system_fonts(self):
  1668. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1669. # 'params': []})
  1670. def connect_toolbar_signals(self):
  1671. """
  1672. Reconnect the signals to the actions in the toolbar.
  1673. This has to be done each time after the FlatCAM tools are removed/installed.
  1674. :return: None
  1675. """
  1676. # Toolbar
  1677. # File Toolbar Signals
  1678. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1679. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1680. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1681. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1682. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1683. # View Toolbar Signals
  1684. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1685. self.ui.replot_btn.triggered.connect(self.plot_all)
  1686. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1687. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1688. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1689. # Edit Toolbar Signals
  1690. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1691. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1692. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1693. self.ui.delete_btn.triggered.connect(self.on_delete)
  1694. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1695. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1696. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1697. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1698. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1699. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1700. # Scripting Toolbar Signals
  1701. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1702. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1703. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1704. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1705. # Tools Toolbar Signals
  1706. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1707. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1708. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1709. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1710. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1711. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1712. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1713. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1714. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1715. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1716. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1717. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1718. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1719. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1720. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1721. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1722. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1723. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1724. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1725. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1726. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1727. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1728. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1729. def object2editor(self):
  1730. """
  1731. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1732. :return: None
  1733. """
  1734. self.defaults.report_usage("object2editor()")
  1735. # disable the objects menu as it may interfere with the appEditors
  1736. self.ui.menuobjects.setDisabled(True)
  1737. edited_object = self.collection.get_active()
  1738. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1739. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1740. pass
  1741. else:
  1742. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1743. return
  1744. if isinstance(edited_object, GeometryObject):
  1745. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1746. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1747. # we set the notebook to hidden
  1748. # self.ui.splitter.setSizes([0, 1])
  1749. if edited_object.multigeo is True:
  1750. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1751. if len(sel_rows) > 1:
  1752. self.inform.emit('[WARNING_NOTCL] %s' %
  1753. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1754. "is not possible.\n"
  1755. "Edit only one geometry at a time."))
  1756. # determine the tool dia of the selected tool
  1757. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1758. # now find the key in the edited_object.tools that has this tooldia
  1759. multi_tool = 1
  1760. for tool in edited_object.tools:
  1761. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1762. multi_tool = tool
  1763. break
  1764. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1765. else:
  1766. self.geo_editor.edit_fcgeometry(edited_object)
  1767. # set call source to the Editor we go into
  1768. self.call_source = 'geo_editor'
  1769. elif isinstance(edited_object, ExcellonObject):
  1770. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1771. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1772. if self.ui.splitter.sizes()[0] == 0:
  1773. self.ui.splitter.setSizes([1, 1])
  1774. self.exc_editor.edit_fcexcellon(edited_object)
  1775. # set call source to the Editor we go into
  1776. self.call_source = 'exc_editor'
  1777. elif isinstance(edited_object, GerberObject):
  1778. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1779. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1780. if self.ui.splitter.sizes()[0] == 0:
  1781. self.ui.splitter.setSizes([1, 1])
  1782. self.grb_editor.edit_fcgerber(edited_object)
  1783. # set call source to the Editor we go into
  1784. self.call_source = 'grb_editor'
  1785. # reset the following variables so the UI is built again after edit
  1786. edited_object.ui_build = False
  1787. edited_object.build_aperture_storage = False
  1788. elif isinstance(edited_object, CNCJobObject):
  1789. if self.ui.splitter.sizes()[0] == 0:
  1790. self.ui.splitter.setSizes([1, 1])
  1791. edited_object.on_edit_code_click()
  1792. return
  1793. # make sure that we can't select another object while in Editor Mode:
  1794. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1795. self.ui.project_frame.setDisabled(True)
  1796. # delete any selection shape that might be active as they are not relevant in Editor
  1797. self.delete_selection_shape()
  1798. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1799. self.ui.plot_tab_area.protectTab(0)
  1800. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1801. self.should_we_save = True
  1802. def editor2object(self, cleanup=None):
  1803. """
  1804. Transfers the Geometry or Excellon from it's editor to the current object.
  1805. :return: None
  1806. """
  1807. self.defaults.report_usage("editor2object()")
  1808. # re-enable the objects menu that was disabled on entry in Editor mode
  1809. self.ui.menuobjects.setDisabled(False)
  1810. # do not update a geometry or excellon object unless it comes out of an editor
  1811. if self.call_source != 'app':
  1812. edited_obj = self.collection.get_active()
  1813. if cleanup is None:
  1814. msgbox = QtWidgets.QMessageBox()
  1815. msgbox.setText(_("Do you want to save the edited object?"))
  1816. msgbox.setWindowTitle(_("Close Editor"))
  1817. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1818. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1819. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1820. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1821. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1822. msgbox.setDefaultButton(bt_yes)
  1823. msgbox.exec_()
  1824. response = msgbox.clickedButton()
  1825. if response == bt_yes:
  1826. # clean the Tools Tab
  1827. self.ui.tool_scroll_area.takeWidget()
  1828. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1829. self.ui.notebook.setTabText(2, "Tool")
  1830. if isinstance(edited_obj, GeometryObject):
  1831. obj_type = "Geometry"
  1832. self.geo_editor.update_fcgeometry(edited_obj)
  1833. # self.geo_editor.update_options(edited_obj)
  1834. # restore GUI to the Selected TAB
  1835. # Remove anything else in the appGUI
  1836. self.ui.tool_scroll_area.takeWidget()
  1837. # update the geo object options so it is including the bounding box values
  1838. try:
  1839. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1840. edited_obj.options['xmin'] = xmin
  1841. edited_obj.options['ymin'] = ymin
  1842. edited_obj.options['xmax'] = xmax
  1843. edited_obj.options['ymax'] = ymax
  1844. except AttributeError as e:
  1845. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1846. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1847. edited_obj.build_ui()
  1848. edited_obj.plot()
  1849. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1850. elif isinstance(edited_obj, GerberObject):
  1851. obj_type = "Gerber"
  1852. self.grb_editor.update_fcgerber()
  1853. # self.grb_editor.update_options(edited_obj)
  1854. # delete the old object (the source object) if it was an empty one
  1855. try:
  1856. if len(edited_obj.solid_geometry) == 0:
  1857. old_name = edited_obj.options['name']
  1858. self.collection.delete_by_name(old_name)
  1859. except TypeError:
  1860. # if the solid_geometry is a single Polygon the len() will not work
  1861. # in any case, falling here means that we have something in the solid_geometry, even if only
  1862. # a single Polygon, therefore we pass this
  1863. pass
  1864. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1865. # restore GUI to the Selected TAB
  1866. # Remove anything else in the appGUI
  1867. self.ui.selected_scroll_area.takeWidget()
  1868. elif isinstance(edited_obj, ExcellonObject):
  1869. obj_type = "Excellon"
  1870. self.exc_editor.update_fcexcellon(edited_obj)
  1871. # self.exc_editor.update_options(edited_obj)
  1872. # restore GUI to the Selected TAB
  1873. # Remove anything else in the appGUI
  1874. self.ui.tool_scroll_area.takeWidget()
  1875. # delete the old object (the source object) if it was an empty one
  1876. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1877. old_name = edited_obj.options['name']
  1878. self.collection.delete_by_name(name=old_name)
  1879. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1880. else:
  1881. self.inform.emit('[WARNING_NOTCL] %s' %
  1882. _("Select a Gerber, Geometry or Excellon Object to update."))
  1883. return
  1884. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1885. elif response == bt_no:
  1886. # clean the Tools Tab
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1889. self.ui.notebook.setTabText(2, "Tool")
  1890. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1891. if isinstance(edited_obj, GeometryObject):
  1892. self.geo_editor.deactivate()
  1893. edited_obj.build_ui()
  1894. edited_obj.plot()
  1895. elif isinstance(edited_obj, GerberObject):
  1896. self.grb_editor.deactivate_grb_editor()
  1897. edited_obj.build_ui()
  1898. elif isinstance(edited_obj, ExcellonObject):
  1899. self.exc_editor.deactivate()
  1900. edited_obj.build_ui()
  1901. else:
  1902. self.inform.emit('[WARNING_NOTCL] %s' %
  1903. _("Select a Gerber, Geometry or Excellon Object to update."))
  1904. return
  1905. elif response == bt_cancel:
  1906. return
  1907. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1908. # edited_obj.build_ui()
  1909. # Switch notebook to Selected page
  1910. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1911. else:
  1912. if isinstance(edited_obj, GeometryObject):
  1913. self.geo_editor.deactivate()
  1914. elif isinstance(edited_obj, GerberObject):
  1915. self.grb_editor.deactivate_grb_editor()
  1916. elif isinstance(edited_obj, ExcellonObject):
  1917. self.exc_editor.deactivate()
  1918. else:
  1919. self.inform.emit('[WARNING_NOTCL] %s' %
  1920. _("Select a Gerber, Geometry or Excellon Object to update."))
  1921. return
  1922. # if notebook is hidden we show it
  1923. if self.ui.splitter.sizes()[0] == 0:
  1924. self.ui.splitter.setSizes([1, 1])
  1925. # restore the call_source to app
  1926. self.call_source = 'app'
  1927. # edited_obj.plot()
  1928. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1929. self.ui.plot_tab_area.protectTab(0)
  1930. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1931. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1932. self.ui.project_frame.setDisabled(False)
  1933. def get_last_folder(self):
  1934. """
  1935. Get the folder path from where the last file was opened.
  1936. :return: String, last opened folder path
  1937. """
  1938. return self.defaults["global_last_folder"]
  1939. def get_last_save_folder(self):
  1940. """
  1941. Get the folder path from where the last file was saved.
  1942. :return: String, last saved folder path
  1943. """
  1944. loc = self.defaults["global_last_save_folder"]
  1945. if loc is None:
  1946. loc = self.defaults["global_last_folder"]
  1947. if loc is None:
  1948. loc = os.path.dirname(__file__)
  1949. return loc
  1950. @QtCore.pyqtSlot(str)
  1951. @QtCore.pyqtSlot(str, bool)
  1952. def info(self, msg, shell_echo=True):
  1953. """
  1954. Informs the user. Normally on the status bar, optionally
  1955. also on the shell.
  1956. :param msg: Text to write.
  1957. :type msg: str
  1958. :param shell_echo: Control if to display the message msg in the Shell
  1959. :type shell_echo: bool
  1960. :return: None
  1961. """
  1962. # Type of message in brackets at the beginning of the message.
  1963. match = re.search(r"\[(.*)\](.*)", msg)
  1964. if match:
  1965. level = match.group(1)
  1966. msg_ = match.group(2)
  1967. self.ui.fcinfo.set_status(str(msg_), level=level)
  1968. if shell_echo is True:
  1969. if level.lower() == "error":
  1970. self.shell_message(msg, error=True, show=True)
  1971. elif level.lower() == "warning":
  1972. self.shell_message(msg, warning=True, show=True)
  1973. elif level.lower() == "error_notcl":
  1974. self.shell_message(msg, error=True, show=False)
  1975. elif level.lower() == "warning_notcl":
  1976. self.shell_message(msg, warning=True, show=False)
  1977. elif level.lower() == "success":
  1978. self.shell_message(msg, success=True, show=False)
  1979. elif level.lower() == "selected":
  1980. self.shell_message(msg, selected=True, show=False)
  1981. else:
  1982. self.shell_message(msg, show=False)
  1983. else:
  1984. self.ui.fcinfo.set_status(str(msg), level="info")
  1985. # make sure that if the message is to clear the infobar with a space
  1986. # is not printed over and over on the shell
  1987. if msg != '' and shell_echo is True:
  1988. self.shell_message(msg)
  1989. def info_shell(self, msg):
  1990. self.shell_message(msg=msg)
  1991. def on_import_preferences(self):
  1992. """
  1993. Loads the application default settings from a saved file into
  1994. ``self.defaults`` dictionary.
  1995. :return: None
  1996. """
  1997. self.defaults.report_usage("on_import_preferences")
  1998. App.log.debug("App.on_import_preferences()")
  1999. # Show file chooser
  2000. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2001. try:
  2002. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2003. directory=self.data_path,
  2004. filter=filter_)
  2005. except TypeError:
  2006. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2007. filter=filter_)
  2008. filename = str(filename)
  2009. if filename == "":
  2010. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2011. return
  2012. # Load in the defaults from the chosen file
  2013. self.defaults.load(filename=filename)
  2014. self.preferencesUiManager.on_preferences_edited()
  2015. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2016. def on_export_preferences(self):
  2017. """
  2018. Save the defaults dictionary to a file.
  2019. :return: None
  2020. """
  2021. self.defaults.report_usage("on_export_preferences")
  2022. App.log.debug("on_export_preferences()")
  2023. # defaults_file_content = None
  2024. # Show file chooser
  2025. date = str(datetime.today()).rpartition('.')[0]
  2026. date = ''.join(c for c in date if c not in ':-')
  2027. date = date.replace(' ', '_')
  2028. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2029. try:
  2030. filename, _f = FCFileSaveDialog.get_saved_filename(
  2031. caption=_("Export FlatCAM Preferences"),
  2032. directory=self.data_path + '/preferences_' + date,
  2033. ext_filter=filter__
  2034. )
  2035. except TypeError:
  2036. filename, _f = FCFileSaveDialog.get_saved_filename(
  2037. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2038. filename = str(filename)
  2039. if filename == "":
  2040. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2041. return
  2042. # Update options
  2043. self.preferencesUiManager.defaults_read_form()
  2044. self.defaults.propagate_defaults()
  2045. # Save update options
  2046. try:
  2047. self.defaults.write(filename=filename)
  2048. except Exception:
  2049. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2050. return
  2051. if self.defaults["global_open_style"] is False:
  2052. self.file_opened.emit("preferences", filename)
  2053. self.file_saved.emit("preferences", filename)
  2054. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2055. def save_to_file(self, content_to_save, txt_content):
  2056. """
  2057. Save something to a file.
  2058. :return: None
  2059. """
  2060. self.defaults.report_usage("save_to_file")
  2061. App.log.debug("save_to_file()")
  2062. self.date = str(datetime.today()).rpartition('.')[0]
  2063. self.date = ''.join(c for c in self.date if c not in ':-')
  2064. self.date = self.date.replace(' ', '_')
  2065. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2066. path_to_save = self.defaults["global_last_save_folder"] if \
  2067. self.defaults["global_last_save_folder"] is not None else self.data_path
  2068. try:
  2069. filename, _f = FCFileSaveDialog.get_saved_filename(
  2070. caption=_("Save to file"),
  2071. directory=path_to_save + '/file_' + self.date,
  2072. ext_filter=filter__
  2073. )
  2074. except TypeError:
  2075. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2076. filename = str(filename)
  2077. if filename == "":
  2078. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2079. return
  2080. else:
  2081. try:
  2082. with open(filename, 'w') as f:
  2083. ___ = f.read()
  2084. except PermissionError:
  2085. self.inform.emit('[WARNING] %s' %
  2086. _("Permission denied, saving not possible.\n"
  2087. "Most likely another app is holding the file open and not accessible."))
  2088. return
  2089. except IOError:
  2090. App.log.debug('Creating a new file ...')
  2091. f = open(filename, 'w')
  2092. f.close()
  2093. except Exception:
  2094. e = sys.exc_info()[0]
  2095. App.log.error("Could not load the file.")
  2096. App.log.error(str(e))
  2097. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2098. return
  2099. # Save content
  2100. if filename.rpartition('.')[2].lower() == 'html':
  2101. file_content = content_to_save
  2102. else:
  2103. file_content = txt_content
  2104. try:
  2105. with open(filename, "w") as f:
  2106. f.write(file_content)
  2107. except Exception:
  2108. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2109. return
  2110. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2111. def register_recent(self, kind, filename):
  2112. """
  2113. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2114. dictionary.
  2115. :param kind: type of file that was opened
  2116. :param filename: the path and file name for the file that was opened
  2117. :return:
  2118. """
  2119. self.log.debug("register_recent()")
  2120. self.log.debug(" %s" % kind)
  2121. self.log.debug(" %s" % filename)
  2122. record = {'kind': str(kind), 'filename': str(filename)}
  2123. if record in self.recent:
  2124. return
  2125. if record in self.recent_projects:
  2126. return
  2127. if record['kind'] == 'project':
  2128. self.recent_projects.insert(0, record)
  2129. else:
  2130. self.recent.insert(0, record)
  2131. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2132. self.recent.pop()
  2133. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2134. self.recent_projects.pop()
  2135. try:
  2136. f = open(self.data_path + '/recent.json', 'w')
  2137. except IOError:
  2138. App.log.error("Failed to open recent items file for writing.")
  2139. self.inform.emit('[ERROR_NOTCL] %s' %
  2140. _('Failed to open recent files file for writing.'))
  2141. return
  2142. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2143. f.close()
  2144. try:
  2145. fp = open(self.data_path + '/recent_projects.json', 'w')
  2146. except IOError:
  2147. App.log.error("Failed to open recent items file for writing.")
  2148. self.inform.emit('[ERROR_NOTCL] %s' %
  2149. _('Failed to open recent projects file for writing.'))
  2150. return
  2151. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2152. fp.close()
  2153. # Re-build the recent items menu
  2154. self.setup_recent_items()
  2155. def on_about(self):
  2156. """
  2157. Displays the "about" dialog found in the Menu --> Help.
  2158. :return: None
  2159. """
  2160. self.defaults.report_usage("on_about")
  2161. version = self.version
  2162. version_date = self.version_date
  2163. beta = self.beta
  2164. class AboutDialog(QtWidgets.QDialog):
  2165. def __init__(self, app, parent=None):
  2166. QtWidgets.QDialog.__init__(self, parent)
  2167. self.app = app
  2168. # Icon and title
  2169. self.setWindowIcon(parent.app_icon)
  2170. self.setWindowTitle(_("About FlatCAM"))
  2171. self.resize(600, 200)
  2172. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2173. # self.setStyleSheet(
  2174. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2175. # "background-attachment: fixed"
  2176. # )
  2177. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2178. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2179. # palette = QtGui.QPalette()
  2180. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2181. # self.setPalette(palette)
  2182. logo = QtWidgets.QLabel()
  2183. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2184. title = QtWidgets.QLabel(
  2185. "<font size=8><B>FlatCAM</B></font><BR>"
  2186. "{title}<BR>"
  2187. "<BR>"
  2188. "<BR>"
  2189. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2190. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2191. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2192. "<B>{issue}</B></a><BR>".format(
  2193. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2194. devel=_("Development"),
  2195. down=_("DOWNLOAD"),
  2196. issue=_("Issue tracker"))
  2197. )
  2198. title.setOpenExternalLinks(True)
  2199. closebtn = QtWidgets.QPushButton(_("Close"))
  2200. tab_widget = QtWidgets.QTabWidget()
  2201. description_label = QtWidgets.QLabel(
  2202. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2203. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2204. version=version,
  2205. beta=('BETA' if beta else ''),
  2206. date=version_date,
  2207. arch=platform.architecture()[0])
  2208. )
  2209. description_label.setOpenExternalLinks(True)
  2210. lic_lbl_header = QtWidgets.QLabel(
  2211. '%s:<br>%s<br>' % (
  2212. _('Licensed under the MIT license'),
  2213. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2214. "http://www.opensource.org/licenses/mit-license.php</a>"
  2215. )
  2216. )
  2217. lic_lbl_header.setOpenExternalLinks(True)
  2218. lic_lbl_body = QtWidgets.QLabel(
  2219. _(
  2220. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2221. 'of this software and associated documentation files (the "Software"), to deal\n'
  2222. 'in the Software without restriction, including without limitation the rights\n'
  2223. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2224. 'copies of the Software, and to permit persons to whom the Software is\n'
  2225. 'furnished to do so, subject to the following conditions:\n\n'
  2226. 'The above copyright notice and this permission notice shall be included in\n'
  2227. 'all copies or substantial portions of the Software.\n\n'
  2228. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2229. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2230. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2231. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2232. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2233. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2234. 'THE SOFTWARE.'
  2235. )
  2236. )
  2237. attributions_label = QtWidgets.QLabel(
  2238. _(
  2239. 'Some of the icons used are from the following sources:<br>'
  2240. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2241. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2242. 'title="Flaticon">www.flaticon.com</a></div>'
  2243. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2244. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2245. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2246. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2247. 'title="Flaticon">www.flaticon.com</a></div>'
  2248. )
  2249. )
  2250. attributions_label.setOpenExternalLinks(True)
  2251. # layouts
  2252. layout1 = QtWidgets.QVBoxLayout()
  2253. layout1_1 = QtWidgets.QHBoxLayout()
  2254. layout1_2 = QtWidgets.QHBoxLayout()
  2255. layout2 = QtWidgets.QHBoxLayout()
  2256. layout3 = QtWidgets.QHBoxLayout()
  2257. self.setLayout(layout1)
  2258. layout1.addLayout(layout1_1)
  2259. layout1.addLayout(layout1_2)
  2260. layout1.addLayout(layout2)
  2261. layout1.addLayout(layout3)
  2262. layout1_1.addStretch()
  2263. layout1_1.addWidget(description_label)
  2264. layout1_2.addWidget(tab_widget)
  2265. self.splash_tab = QtWidgets.QWidget()
  2266. self.splash_tab.setObjectName("splash_about")
  2267. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2268. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2269. tab_widget.addTab(self.splash_tab, _("Splash"))
  2270. self.programmmers_tab = QtWidgets.QWidget()
  2271. self.programmmers_tab.setObjectName("programmers_about")
  2272. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2273. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2274. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2275. self.translators_tab = QtWidgets.QWidget()
  2276. self.translators_tab.setObjectName("translators_about")
  2277. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2278. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2279. tab_widget.addTab(self.translators_tab, _("Translators"))
  2280. self.license_tab = QtWidgets.QWidget()
  2281. self.license_tab.setObjectName("license_about")
  2282. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2283. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2284. tab_widget.addTab(self.license_tab, _("License"))
  2285. self.attributions_tab = QtWidgets.QWidget()
  2286. self.attributions_tab.setObjectName("attributions_about")
  2287. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2288. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2289. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2290. self.splash_tab_layout.addWidget(logo, stretch=0)
  2291. self.splash_tab_layout.addWidget(title, stretch=1)
  2292. pal = QtGui.QPalette()
  2293. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2294. self.prog_grid_lay = QtWidgets.QGridLayout()
  2295. self.prog_grid_lay.setHorizontalSpacing(20)
  2296. self.prog_grid_lay.setColumnStretch(0, 0)
  2297. self.prog_grid_lay.setColumnStretch(2, 1)
  2298. prog_widget = QtWidgets.QWidget()
  2299. prog_widget.setLayout(self.prog_grid_lay)
  2300. prog_scroll = QtWidgets.QScrollArea()
  2301. prog_scroll.setWidget(prog_widget)
  2302. prog_scroll.setWidgetResizable(True)
  2303. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2304. prog_scroll.setPalette(pal)
  2305. self.programmmers_tab_layout.addWidget(prog_scroll)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2353. self.translator_grid_lay = QtWidgets.QGridLayout()
  2354. self.translator_grid_lay.setColumnStretch(0, 0)
  2355. self.translator_grid_lay.setColumnStretch(1, 0)
  2356. self.translator_grid_lay.setColumnStretch(2, 1)
  2357. self.translator_grid_lay.setColumnStretch(3, 0)
  2358. # trans_widget = QtWidgets.QWidget()
  2359. # trans_widget.setLayout(self.translator_grid_lay)
  2360. # self.translators_tab_layout.addWidget(trans_widget)
  2361. # self.translators_tab_layout.addStretch()
  2362. trans_widget = QtWidgets.QWidget()
  2363. trans_widget.setLayout(self.translator_grid_lay)
  2364. trans_scroll = QtWidgets.QScrollArea()
  2365. trans_scroll.setWidget(trans_widget)
  2366. trans_scroll.setWidgetResizable(True)
  2367. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2368. trans_scroll.setPalette(pal)
  2369. self.translators_tab_layout.addWidget(trans_scroll)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2403. self.translator_grid_lay.setColumnStretch(0, 0)
  2404. self.translators_tab_layout.addStretch()
  2405. self.license_tab_layout.addWidget(lic_lbl_header)
  2406. self.license_tab_layout.addWidget(lic_lbl_body)
  2407. self.license_tab_layout.addStretch()
  2408. self.attributions_tab_layout.addWidget(attributions_label)
  2409. self.attributions_tab_layout.addStretch()
  2410. layout3.addStretch()
  2411. layout3.addWidget(closebtn)
  2412. closebtn.clicked.connect(self.accept)
  2413. AboutDialog(app=self, parent=self.ui).exec_()
  2414. def on_readme(self):
  2415. """
  2416. Displays the "about" dialog found in the Menu --> Help.
  2417. :return: None
  2418. """
  2419. class ReadmeDialog(QtWidgets.QDialog):
  2420. def __init__(self, app, parent=None):
  2421. QtWidgets.QDialog.__init__(self, parent)
  2422. self.app = app
  2423. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2424. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2425. "<b>click</b></a>"
  2426. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2427. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2428. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2429. # Icon and title
  2430. self.setWindowIcon(parent.app_icon)
  2431. self.setWindowTitle(_("Important Information's"))
  2432. self.resize(750, 375)
  2433. logo = QtWidgets.QLabel()
  2434. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2435. content = QtWidgets.QLabel(
  2436. "%s<br>"
  2437. "%s<br><br>"
  2438. "%s,<br>"
  2439. "%s<br>"
  2440. "<ul>"
  2441. "<li> &nbsp;%s %s</li>"
  2442. "<li> &nbsp;%s %s</li>"
  2443. "</ul>"
  2444. "%s %s.<br>"
  2445. "%s"
  2446. "<ul>"
  2447. "<li> &nbsp;%s &#128077;</li>"
  2448. "<li> &nbsp;%s &#128513;</li>"
  2449. "</ul>" %
  2450. (
  2451. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2452. _("Yet it cannot evolve without <b>contributions</b>."),
  2453. _("If you want to see this application grow and become better and better"),
  2454. _("you can <b>contribute</b> to the development yourself by:"),
  2455. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2456. new_features_link,
  2457. _("Bug Reports by providing the steps required to reproduce the bug"),
  2458. bugs_link,
  2459. _("If you like or use this program you can make a donation"),
  2460. donation_link,
  2461. _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2462. _("it will be welcomed with joy"),
  2463. _("it will give me a reason to continue")
  2464. )
  2465. )
  2466. content.setOpenExternalLinks(True)
  2467. # palette
  2468. pal = QtGui.QPalette()
  2469. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2470. # layouts
  2471. main_layout = QtWidgets.QVBoxLayout()
  2472. self.setLayout(main_layout)
  2473. tab_layout = QtWidgets.QHBoxLayout()
  2474. buttons_hlay = QtWidgets.QHBoxLayout()
  2475. main_layout.addLayout(tab_layout)
  2476. main_layout.addLayout(buttons_hlay)
  2477. tab_widget = QtWidgets.QTabWidget()
  2478. tab_layout.addWidget(tab_widget)
  2479. closebtn = QtWidgets.QPushButton(_("Close"))
  2480. buttons_hlay.addStretch()
  2481. buttons_hlay.addWidget(closebtn)
  2482. # CONTRIBUTE section
  2483. self.intro_tab = QtWidgets.QWidget()
  2484. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2485. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2486. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2487. self.grid_lay = QtWidgets.QGridLayout()
  2488. self.grid_lay.setHorizontalSpacing(20)
  2489. self.grid_lay.setColumnStretch(0, 0)
  2490. self.grid_lay.setColumnStretch(1, 1)
  2491. intro_wdg = QtWidgets.QWidget()
  2492. intro_wdg.setLayout(self.grid_lay)
  2493. intro_scroll_area = QtWidgets.QScrollArea()
  2494. intro_scroll_area.setWidget(intro_wdg)
  2495. intro_scroll_area.setWidgetResizable(True)
  2496. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2497. intro_scroll_area.setPalette(pal)
  2498. self.grid_lay.addWidget(logo, 0, 0)
  2499. self.grid_lay.addWidget(content, 0, 1)
  2500. self.intro_tab_layout.addWidget(intro_scroll_area)
  2501. # LINKS EXCHANGE section
  2502. self.links_tab = QtWidgets.QWidget()
  2503. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2504. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2505. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2506. self.links_lay = QtWidgets.QHBoxLayout()
  2507. links_wdg = QtWidgets.QWidget()
  2508. links_wdg.setLayout(self.links_lay)
  2509. links_scroll_area = QtWidgets.QScrollArea()
  2510. links_scroll_area.setWidget(links_wdg)
  2511. links_scroll_area.setWidgetResizable(True)
  2512. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2513. links_scroll_area.setPalette(pal)
  2514. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2515. self.links_tab_layout.addWidget(links_scroll_area)
  2516. # HOW TO section
  2517. self.howto_tab = QtWidgets.QWidget()
  2518. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2519. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2520. tab_widget.addTab(self.howto_tab, _("How To's"))
  2521. self.howto_lay = QtWidgets.QHBoxLayout()
  2522. howto_wdg = QtWidgets.QWidget()
  2523. howto_wdg.setLayout(self.howto_lay)
  2524. howto_scroll_area = QtWidgets.QScrollArea()
  2525. howto_scroll_area.setWidget(howto_wdg)
  2526. howto_scroll_area.setWidgetResizable(True)
  2527. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2528. howto_scroll_area.setPalette(pal)
  2529. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2530. self.howto_tab_layout.addWidget(howto_scroll_area)
  2531. # BUTTONS section
  2532. closebtn.clicked.connect(self.accept)
  2533. ReadmeDialog(app=self, parent=self.ui).exec_()
  2534. def install_bookmarks(self, book_dict=None):
  2535. """
  2536. Install the bookmarks actions in the Help menu -> Bookmarks
  2537. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2538. :return: None
  2539. """
  2540. if book_dict is None:
  2541. self.defaults["global_bookmarks"].update(
  2542. {
  2543. '1': ['FlatCAM', "http://flatcam.org"],
  2544. '2': ['Backup Site', ""]
  2545. }
  2546. )
  2547. else:
  2548. self.defaults["global_bookmarks"].clear()
  2549. self.defaults["global_bookmarks"].update(book_dict)
  2550. # first try to disconnect if somehow they get connected from elsewhere
  2551. for act in self.ui.menuhelp_bookmarks.actions():
  2552. try:
  2553. act.triggered.disconnect()
  2554. except TypeError:
  2555. pass
  2556. # clear all actions except the last one who is the Bookmark manager
  2557. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2558. pass
  2559. else:
  2560. self.ui.menuhelp_bookmarks.removeAction(act)
  2561. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2562. if self.defaults["global_bookmarks"]:
  2563. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2564. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2565. # the JSON is first making the keys as strings (therefore I have to use strings too
  2566. # or do the conversion :(
  2567. # )
  2568. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2569. # the '10' entry jsut after '1' therefore ordering as strings
  2570. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2571. key=lambda x: int(x[0]))
  2572. for entry, bookmark in sorted_bookmarks:
  2573. title = bookmark[0]
  2574. weblink = bookmark[1]
  2575. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2576. act.setText(title)
  2577. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2578. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2579. if title == 'Backup Site' and weblink == "":
  2580. act.triggered.connect(self.on_backup_site)
  2581. else:
  2582. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2583. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2584. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2585. def on_bookmarks_manager(self):
  2586. """
  2587. Adds the bookmark manager in a Tab in Plot Area
  2588. :return:
  2589. """
  2590. for idx in range(self.ui.plot_tab_area.count()):
  2591. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2592. # there can be only one instance of Bookmark Manager at one time
  2593. return
  2594. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2595. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2596. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2597. # add the tab if it was closed
  2598. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2599. # delete the absolute and relative position and messages in the infobar
  2600. self.ui.position_label.setText("")
  2601. # self.ui.rel_position_label.setText("")
  2602. # Switch plot_area to preferences page
  2603. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2604. def on_backup_site(self):
  2605. msgbox = QtWidgets.QMessageBox()
  2606. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2607. "1. FlatCAM.org website is down\n"
  2608. "2. Someone forked FlatCAM project and wants to point\n"
  2609. "to his own website\n\n"
  2610. "If you can't get any informations about FlatCAM beta\n"
  2611. "use the YouTube channel link from the Help menu."))
  2612. msgbox.setWindowTitle(_("Alternative website"))
  2613. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2614. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2615. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2616. msgbox.setDefaultButton(bt_yes)
  2617. msgbox.exec_()
  2618. # response = msgbox.clickedButton()
  2619. def on_file_savedefaults(self):
  2620. """
  2621. Callback for menu item File->Save Defaults. Saves application default options
  2622. ``self.defaults`` to current_defaults.FlatConfig.
  2623. :return: None
  2624. """
  2625. self.preferencesUiManager.save_defaults()
  2626. def final_save(self):
  2627. """
  2628. Callback for doing a preferences save to file whenever the application is about to quit.
  2629. If the project has changes, it will ask the user to save the project.
  2630. :return: None
  2631. """
  2632. if self.save_in_progress:
  2633. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2634. return
  2635. if self.should_we_save and self.collection.get_list():
  2636. msgbox = QtWidgets.QMessageBox()
  2637. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2638. "\n"
  2639. "Do you want to Save the project?"))
  2640. msgbox.setWindowTitle(_("Save changes"))
  2641. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2642. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2643. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2644. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2645. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2646. msgbox.setDefaultButton(bt_yes)
  2647. msgbox.exec_()
  2648. response = msgbox.clickedButton()
  2649. if response == bt_yes:
  2650. try:
  2651. self.trayIcon.hide()
  2652. except Exception:
  2653. pass
  2654. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2655. elif response == bt_no:
  2656. try:
  2657. self.trayIcon.hide()
  2658. except Exception:
  2659. pass
  2660. self.quit_application()
  2661. elif response == bt_cancel:
  2662. return
  2663. else:
  2664. try:
  2665. self.trayIcon.hide()
  2666. except Exception:
  2667. pass
  2668. self.quit_application()
  2669. def quit_application(self):
  2670. """
  2671. Called (as a pyslot or not) when the application is quit.
  2672. :return: None
  2673. """
  2674. # close editors before quiting the app, if they are open
  2675. if self.geo_editor.editor_active is True:
  2676. self.geo_editor.deactivate()
  2677. try:
  2678. self.geo_editor.disconnect()
  2679. except TypeError:
  2680. pass
  2681. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2682. if self.exc_editor.editor_active is True:
  2683. self.exc_editor.deactivate()
  2684. try:
  2685. self.grb_editor.disconnect()
  2686. except TypeError:
  2687. pass
  2688. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2689. if self.grb_editor.editor_active is True:
  2690. self.grb_editor.deactivate_grb_editor()
  2691. try:
  2692. self.exc_editor.disconnect()
  2693. except TypeError:
  2694. pass
  2695. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2696. # disconnect the mouse events
  2697. if self.is_legacy:
  2698. self.plotcanvas.graph_event_disconnect(self.mm)
  2699. self.plotcanvas.graph_event_disconnect(self.mp)
  2700. self.plotcanvas.graph_event_disconnect(self.mr)
  2701. self.plotcanvas.graph_event_disconnect(self.mdc)
  2702. self.plotcanvas.graph_event_disconnect(self.kp)
  2703. else:
  2704. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2705. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2706. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2707. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2708. self.on_mouse_double_click_over_plot)
  2709. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2710. self.preferencesUiManager.save_defaults(silent=True)
  2711. log.debug("App.quit_application() --> App Defaults saved.")
  2712. if self.cmd_line_headless != 1:
  2713. # save app state to file
  2714. stgs = QSettings("Open Source", "FlatCAM")
  2715. stgs.setValue('saved_gui_state', self.ui.saveState())
  2716. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2717. stgs.setValue(
  2718. 'language',
  2719. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2720. )
  2721. stgs.setValue(
  2722. 'notebook_font_size',
  2723. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2724. )
  2725. stgs.setValue(
  2726. 'axis_font_size',
  2727. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2728. )
  2729. stgs.setValue(
  2730. 'textbox_font_size',
  2731. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2732. )
  2733. stgs.setValue(
  2734. 'hud_font_size',
  2735. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2736. )
  2737. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2738. stgs.setValue(
  2739. 'machinist',
  2740. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2741. )
  2742. # This will write the setting to the platform specific storage.
  2743. del stgs
  2744. log.debug("App.quit_application() --> App UI state saved.")
  2745. # try to quit the Socket opened by ArgsThread class
  2746. try:
  2747. # self.new_launch.thread_exit = True
  2748. # self.new_launch.listener.close()
  2749. self.new_launch.stop.emit()
  2750. except Exception as err:
  2751. log.debug("App.quit_application() --> %s" % str(err))
  2752. # try to quit the QThread that run ArgsThread class
  2753. try:
  2754. # del self.new_launch
  2755. self.listen_th.quit()
  2756. except Exception as e:
  2757. log.debug("App.quit_application() --> %s" % str(e))
  2758. # terminate workers
  2759. # self.workers.__del__()
  2760. self.clear_pool()
  2761. # quit app by signalling for self.kill_app() method
  2762. # self.close_app_signal.emit()
  2763. QtWidgets.qApp.quit()
  2764. # QtCore.QCoreApplication.quit()
  2765. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2766. # we use the following command
  2767. minor_v = sys.version_info.minor
  2768. if minor_v < 8:
  2769. # make sure that the app closes
  2770. sys.exit(0)
  2771. else:
  2772. os._exit(0) # fix to work with Python 3.8
  2773. @staticmethod
  2774. def kill_app():
  2775. QtWidgets.qApp.quit()
  2776. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2777. # we use the following command
  2778. sys.exit(0)
  2779. def on_portable_checked(self, state):
  2780. """
  2781. Callback called when the checkbox in Preferences GUI is checked.
  2782. It will set the application as portable by creating the preferences and recent files in the
  2783. 'config' folder found in the FlatCAM installation folder.
  2784. :param state: boolean, the state of the checkbox when clicked/checked
  2785. :return:
  2786. """
  2787. line_no = 0
  2788. data = None
  2789. if sys.platform != 'win32':
  2790. # this won't work in Linux or MacOS
  2791. return
  2792. # test if the app was frozen and choose the path for the configuration file
  2793. if getattr(sys, "frozen", False) is True:
  2794. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2795. else:
  2796. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2797. config_file = current_data_path + '\\configuration.txt'
  2798. try:
  2799. with open(config_file, 'r') as f:
  2800. try:
  2801. data = f.readlines()
  2802. except Exception as e:
  2803. log.debug('App.__init__() -->%s' % str(e))
  2804. return
  2805. except FileNotFoundError:
  2806. pass
  2807. for line in data:
  2808. line = line.strip('\n')
  2809. param = str(line).rpartition('=')
  2810. if param[0] == 'portable':
  2811. break
  2812. line_no += 1
  2813. if state:
  2814. data[line_no] = 'portable=True\n'
  2815. # create the new defauults files
  2816. # create current_defaults.FlatConfig file if there is none
  2817. try:
  2818. f = open(current_data_path + '/current_defaults.FlatConfig')
  2819. f.close()
  2820. except IOError:
  2821. App.log.debug('Creating empty current_defaults.FlatConfig')
  2822. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2823. json.dump({}, f)
  2824. f.close()
  2825. # create factory_defaults.FlatConfig file if there is none
  2826. try:
  2827. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2828. f.close()
  2829. except IOError:
  2830. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2831. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2832. json.dump({}, f)
  2833. f.close()
  2834. try:
  2835. f = open(current_data_path + '/recent.json')
  2836. f.close()
  2837. except IOError:
  2838. App.log.debug('Creating empty recent.json')
  2839. f = open(current_data_path + '/recent.json', 'w')
  2840. json.dump([], f)
  2841. f.close()
  2842. try:
  2843. fp = open(current_data_path + '/recent_projects.json')
  2844. fp.close()
  2845. except IOError:
  2846. App.log.debug('Creating empty recent_projects.json')
  2847. fp = open(current_data_path + '/recent_projects.json', 'w')
  2848. json.dump([], fp)
  2849. fp.close()
  2850. # save the current defaults to the new defaults file
  2851. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2852. else:
  2853. data[line_no] = 'portable=False\n'
  2854. with open(config_file, 'w') as f:
  2855. f.writelines(data)
  2856. def on_register_files(self, obj_type=None):
  2857. """
  2858. Called whenever there is a need to register file extensions with FlatCAM.
  2859. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2860. :param obj_type: the type of object to be register for.
  2861. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2862. :return: None
  2863. """
  2864. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2865. new_reg_path = 'Software\\Classes\\'
  2866. # find if the current user is admin
  2867. try:
  2868. is_admin = os.getuid() == 0
  2869. except AttributeError:
  2870. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2871. if is_admin is True:
  2872. root_path = winreg.HKEY_LOCAL_MACHINE
  2873. else:
  2874. root_path = winreg.HKEY_CURRENT_USER
  2875. # create the keys
  2876. def set_reg(name, root_pth, new_reg_path, value):
  2877. try:
  2878. winreg.CreateKey(root_pth, new_reg_path)
  2879. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2880. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2881. return True
  2882. except WindowsError:
  2883. return False
  2884. # delete key in registry
  2885. def delete_reg(root_pth, reg_path, key_to_del):
  2886. key_to_del_path = reg_path + key_to_del
  2887. try:
  2888. winreg.DeleteKey(root_pth, key_to_del_path)
  2889. return True
  2890. except WindowsError:
  2891. return False
  2892. if obj_type is None or obj_type == 'excellon':
  2893. exc_list = \
  2894. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2895. exc_list = [x for x in exc_list if x != '']
  2896. # register all keys in the Preferences window
  2897. for ext in exc_list:
  2898. new_k = new_reg_path + '.%s' % ext
  2899. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2900. # and unregister those that are no longer in the Preferences windows but are in the file
  2901. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2902. if ext not in exc_list:
  2903. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2904. # now write the updated extensions to the self.defaults
  2905. # new_ext = ''
  2906. # for ext in exc_list:
  2907. # new_ext = new_ext + ext + ', '
  2908. # self.defaults["fa_excellon"] = new_ext
  2909. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2910. if obj_type is None or obj_type == 'gcode':
  2911. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2912. gco_list = [x for x in gco_list if x != '']
  2913. # register all keys in the Preferences window
  2914. for ext in gco_list:
  2915. new_k = new_reg_path + '.%s' % ext
  2916. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2917. # and unregister those that are no longer in the Preferences windows but are in the file
  2918. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2919. if ext not in gco_list:
  2920. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2921. # now write the updated extensions to the self.defaults
  2922. # new_ext = ''
  2923. # for ext in gco_list:
  2924. # new_ext = new_ext + ext + ', '
  2925. # self.defaults["fa_gcode"] = new_ext
  2926. self.inform.emit('[success] %s' %
  2927. _("Selected GCode file extensions registered with FlatCAM."))
  2928. if obj_type is None or obj_type == 'gerber':
  2929. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2930. grb_list = [x for x in grb_list if x != '']
  2931. # register all keys in the Preferences window
  2932. for ext in grb_list:
  2933. new_k = new_reg_path + '.%s' % ext
  2934. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2935. # and unregister those that are no longer in the Preferences windows but are in the file
  2936. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2937. if ext not in grb_list:
  2938. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2939. # now write the updated extensions to the self.defaults
  2940. # new_ext = ''
  2941. # for ext in grb_list:
  2942. # new_ext = new_ext + ext + ', '
  2943. # self.defaults["fa_gerber"] = new_ext
  2944. self.inform.emit('[success] %s' %
  2945. _("Selected Gerber file extensions registered with FlatCAM."))
  2946. def add_extension(self, ext_type):
  2947. """
  2948. Add a file extension to the list for a specific object
  2949. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2950. :return:
  2951. """
  2952. if ext_type == 'excellon':
  2953. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2954. if new_ext == '':
  2955. return
  2956. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2957. if new_ext in old_val:
  2958. return
  2959. old_val.append(new_ext)
  2960. old_val.sort()
  2961. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2962. if ext_type == 'gcode':
  2963. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2964. if new_ext == '':
  2965. return
  2966. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2967. if new_ext in old_val:
  2968. return
  2969. old_val.append(new_ext)
  2970. old_val.sort()
  2971. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2972. if ext_type == 'gerber':
  2973. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2974. if new_ext == '':
  2975. return
  2976. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2977. if new_ext in old_val:
  2978. return
  2979. old_val.append(new_ext)
  2980. old_val.sort()
  2981. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2982. if ext_type == 'keyword':
  2983. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2984. if new_kw == '':
  2985. return
  2986. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2987. if new_kw in old_val:
  2988. return
  2989. old_val.append(new_kw)
  2990. old_val.sort()
  2991. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2992. # update the self.myKeywords so the model is updated
  2993. self.autocomplete_kw_list = \
  2994. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2995. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2996. self.shell._edit.set_model_data(self.myKeywords)
  2997. def del_extension(self, ext_type):
  2998. """
  2999. Remove a file extension from the list for a specific object
  3000. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3001. :return:
  3002. """
  3003. if ext_type == 'excellon':
  3004. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3005. if new_ext == '':
  3006. return
  3007. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3008. if new_ext not in old_val:
  3009. return
  3010. old_val.remove(new_ext)
  3011. old_val.sort()
  3012. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3013. if ext_type == 'gcode':
  3014. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3015. if new_ext == '':
  3016. return
  3017. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3018. if new_ext not in old_val:
  3019. return
  3020. old_val.remove(new_ext)
  3021. old_val.sort()
  3022. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3023. if ext_type == 'gerber':
  3024. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3025. if new_ext == '':
  3026. return
  3027. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3028. if new_ext not in old_val:
  3029. return
  3030. old_val.remove(new_ext)
  3031. old_val.sort()
  3032. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3033. if ext_type == 'keyword':
  3034. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3035. if new_kw == '':
  3036. return
  3037. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3038. if new_kw not in old_val:
  3039. return
  3040. old_val.remove(new_kw)
  3041. old_val.sort()
  3042. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3043. # update the self.myKeywords so the model is updated
  3044. self.autocomplete_kw_list = \
  3045. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3046. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3047. self.shell._edit.set_model_data(self.myKeywords)
  3048. def restore_extensions(self, ext_type):
  3049. """
  3050. Restore all file extensions associations with FlatCAM, for a specific object
  3051. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3052. :return:
  3053. """
  3054. if ext_type == 'excellon':
  3055. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3056. # for the ability to open Excellon files with .txt extension
  3057. new_exc_list = deepcopy(self.exc_list)
  3058. try:
  3059. new_exc_list.remove('txt')
  3060. except ValueError:
  3061. pass
  3062. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3063. if ext_type == 'gcode':
  3064. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3065. if ext_type == 'gerber':
  3066. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3067. if ext_type == 'keyword':
  3068. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3069. # update the self.myKeywords so the model is updated
  3070. self.autocomplete_kw_list = self.default_keywords
  3071. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3072. self.shell._edit.set_model_data(self.myKeywords)
  3073. def delete_all_extensions(self, ext_type):
  3074. """
  3075. Delete all file extensions associations with FlatCAM, for a specific object
  3076. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3077. :return:
  3078. """
  3079. if ext_type == 'excellon':
  3080. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3081. if ext_type == 'gcode':
  3082. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3083. if ext_type == 'gerber':
  3084. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3085. if ext_type == 'keyword':
  3086. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3087. # update the self.myKeywords so the model is updated
  3088. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3089. self.shell._edit.set_model_data(self.myKeywords)
  3090. def on_edit_join(self, name=None):
  3091. """
  3092. Callback for Edit->Join. Joins the selected geometry objects into
  3093. a new one.
  3094. :return: None
  3095. """
  3096. self.defaults.report_usage("on_edit_join()")
  3097. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3098. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3099. geo_type_set = set()
  3100. objs = self.collection.get_selected()
  3101. if len(objs) < 2:
  3102. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3103. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3104. return 'fail'
  3105. for obj in objs:
  3106. geo_type_set.add(obj.multigeo)
  3107. # if len(geo_type_list) == 1 means that all list elements are the same
  3108. if len(geo_type_set) != 1:
  3109. self.inform.emit('[ERROR] %s' %
  3110. _("Failed join. The Geometry objects are of different types.\n"
  3111. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3112. "convert from one to another and retry joining \n"
  3113. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3114. "the result may not be what was expected. \n"
  3115. "Check the generated GCODE."))
  3116. return
  3117. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3118. if True in geo_type_set:
  3119. def initialize(geo_obj, app):
  3120. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3121. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3122. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3123. for v in geo_obj.tools.values():
  3124. v['data']['name'] = obj_name_multi
  3125. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3126. else:
  3127. def initialize(geo_obj, app):
  3128. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3129. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3130. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3131. for v in geo_obj.tools.values():
  3132. v['data']['name'] = obj_name_single
  3133. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3134. self.should_we_save = True
  3135. def on_edit_join_exc(self):
  3136. """
  3137. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3138. a new Excellon.
  3139. :return: None
  3140. """
  3141. self.defaults.report_usage("on_edit_join_exc()")
  3142. objs = self.collection.get_selected()
  3143. for obj in objs:
  3144. if not isinstance(obj, ExcellonObject):
  3145. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3146. return
  3147. if len(objs) < 2:
  3148. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3149. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3150. return 'fail'
  3151. def initialize(exc_obj, app):
  3152. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3153. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3154. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3155. self.should_we_save = True
  3156. def on_edit_join_grb(self):
  3157. """
  3158. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3159. a new Gerber object.
  3160. :return: None
  3161. """
  3162. self.defaults.report_usage("on_edit_join_grb()")
  3163. objs = self.collection.get_selected()
  3164. for obj in objs:
  3165. if not isinstance(obj, GerberObject):
  3166. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3167. return
  3168. if len(objs) < 2:
  3169. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3170. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3171. return 'fail'
  3172. def initialize(grb_obj, app):
  3173. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3174. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3175. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3176. self.should_we_save = True
  3177. def on_convert_singlegeo_to_multigeo(self):
  3178. """
  3179. Called for converting a Geometry object from single-geo to multi-geo.
  3180. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3181. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3182. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3183. the solid-geometry of that tool.
  3184. :return: None
  3185. """
  3186. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3187. obj = self.collection.get_active()
  3188. if obj is None:
  3189. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3190. return
  3191. if not isinstance(obj, GeometryObject):
  3192. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3193. return
  3194. obj.multigeo = True
  3195. for tooluid, dict_value in obj.tools.items():
  3196. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3197. if not isinstance(obj.solid_geometry, list):
  3198. obj.solid_geometry = [obj.solid_geometry]
  3199. # obj.solid_geometry[:] = []
  3200. obj.plot()
  3201. self.should_we_save = True
  3202. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3203. def on_convert_multigeo_to_singlegeo(self):
  3204. """
  3205. Called for converting a Geometry object from multi-geo to single-geo.
  3206. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3207. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3208. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3209. the solid-geometry of that tool.
  3210. :return: None
  3211. """
  3212. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3213. obj = self.collection.get_active()
  3214. if obj is None:
  3215. self.inform.emit('[ERROR_NOTCL] %s' %
  3216. _("Failed. Select a Geometry Object and try again."))
  3217. return
  3218. if not isinstance(obj, GeometryObject):
  3219. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3220. (_("Expected a GeometryObject, got"), type(obj)))
  3221. return
  3222. obj.multigeo = False
  3223. total_solid_geometry = []
  3224. for tooluid, dict_value in obj.tools.items():
  3225. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3226. # clear the original geometry
  3227. dict_value['solid_geometry'][:] = []
  3228. obj.solid_geometry = deepcopy(total_solid_geometry)
  3229. obj.plot()
  3230. self.should_we_save = True
  3231. self.inform.emit('[success] %s' %
  3232. _("A Geometry object was converted to SingleGeo type."))
  3233. def on_defaults_dict_change(self, field):
  3234. """
  3235. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3236. Edit -> Preferences tab window.
  3237. :param field: the key of the self.defaults dictionary that was changed.
  3238. :return: None
  3239. """
  3240. self.preferencesUiManager.defaults_write_form_field(field=field)
  3241. if field == "units":
  3242. self.set_screen_units(self.defaults['units'])
  3243. def set_screen_units(self, units):
  3244. """
  3245. Set the FlatCAM units on the status bar.
  3246. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3247. :return: None
  3248. """
  3249. self.ui.units_label.setText("[" + units.lower() + "]")
  3250. def on_toggle_units_click(self):
  3251. try:
  3252. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3253. except (TypeError, AttributeError):
  3254. pass
  3255. if self.defaults["units"] == 'MM':
  3256. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3257. else:
  3258. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3259. self.on_toggle_units(no_pref=True)
  3260. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3261. lambda: self.on_toggle_units(no_pref=False))
  3262. def on_toggle_units(self, no_pref=False):
  3263. """
  3264. Callback for the Units radio-button change in the Preferences tab.
  3265. Changes the application's default units adn for the project too.
  3266. If changing the project's units, the change propagates to all of
  3267. the objects in the project.
  3268. :return: None
  3269. """
  3270. self.defaults.report_usage("on_toggle_units")
  3271. if self.toggle_units_ignore:
  3272. return
  3273. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3274. # If option is the same, then ignore
  3275. if new_units == self.defaults["units"].upper():
  3276. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3277. return
  3278. # Keys in self.defaults for which to scale their values
  3279. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3280. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3281. "tools_iso_tool_vtipdia",
  3282. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3283. "gerber_editor_ma_high",
  3284. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3285. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3286. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3287. "excellon_feedrate_probe", "excellon_milling_dia",
  3288. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3289. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3290. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3291. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3292. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3293. "geometry_extracut_length", "geometry_z_pdepth",
  3294. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3295. 'cncjob_tooldia',
  3296. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3297. "tools_paintnewdia",
  3298. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3299. "tools_nccnewdia", "tools_ncc_offset_value",
  3300. "tools_2sided_drilldia",
  3301. "tools_film_boundary", "tools_film_scale_stroke",
  3302. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3303. "tools_cutout_depthperpass",
  3304. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3305. "tools_panelize_spacing_rows",
  3306. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3307. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3308. "tools_transform_buffer_dis",
  3309. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3310. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3311. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3312. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3313. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3314. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3315. "tools_cr_h2h_val", "tools_cr_dh_val",
  3316. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3317. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3318. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3319. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3320. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3321. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3322. "tools_copper_thieving_mask_clearance",
  3323. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3324. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3325. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3326. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3327. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3328. "tools_invert_margin",
  3329. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3330. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3331. def scale_defaults(sfactor):
  3332. for dim in dimensions:
  3333. if dim in [
  3334. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3335. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3336. 'tools_transform_mirror_point'
  3337. ]:
  3338. if self.defaults[dim] is None or self.defaults[dim] == '':
  3339. continue
  3340. try:
  3341. coordinates = self.defaults[dim].split(",")
  3342. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3343. coords_xy[0] *= sfactor
  3344. coords_xy[1] *= sfactor
  3345. self.defaults[dim] = "%.*f, %.*f" % (
  3346. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3347. except Exception as e:
  3348. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3349. elif dim in [
  3350. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3351. ]:
  3352. if self.defaults[dim] is None or self.defaults[dim] == '':
  3353. continue
  3354. try:
  3355. self.defaults[dim] = float(self.defaults[dim])
  3356. tools_diameters = [self.defaults[dim]]
  3357. except ValueError:
  3358. try:
  3359. tools_string = self.defaults[dim].split(",")
  3360. tools_diameters = [eval(a) for a in tools_string if a != '']
  3361. except Exception as e:
  3362. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3363. continue
  3364. self.defaults[dim] = ''
  3365. td_len = len(tools_diameters)
  3366. if td_len > 1:
  3367. for t in range(td_len):
  3368. tools_diameters[t] *= sfactor
  3369. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3370. else:
  3371. tools_diameters[0] *= sfactor
  3372. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3373. elif dim in ['global_gridx', 'global_gridy']:
  3374. # format the number of decimals to the one specified in self.decimals
  3375. try:
  3376. val = float(self.defaults[dim]) * sfactor
  3377. except Exception as e:
  3378. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3379. continue
  3380. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3381. else:
  3382. # the number of decimals for the rest is kept unchanged
  3383. if self.defaults[dim]:
  3384. try:
  3385. val = float(self.defaults[dim]) * sfactor
  3386. except Exception as e:
  3387. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3388. continue
  3389. self.defaults[dim] = val
  3390. # The scaling factor depending on choice of units.
  3391. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3392. # Changing project units. Warn user.
  3393. msgbox = QtWidgets.QMessageBox()
  3394. msgbox.setWindowTitle(_("Toggle Units"))
  3395. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3396. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3397. msgbox.setText(_("Changing the units of the project\n"
  3398. "will scale all objects.\n\n"
  3399. "Do you want to continue?"))
  3400. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3401. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3402. msgbox.setDefaultButton(bt_ok)
  3403. msgbox.exec_()
  3404. response = msgbox.clickedButton()
  3405. if response == bt_ok:
  3406. if no_pref is False:
  3407. self.preferencesUiManager.defaults_read_form()
  3408. scale_defaults(factor)
  3409. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3410. self.defaults["units"] = new_units
  3411. # update the defaults from form, some may assume that the conversion is enough and it's not
  3412. self.on_options_app2project()
  3413. # update the objects
  3414. for obj in self.collection.get_list():
  3415. obj.convert_units(new_units)
  3416. # make that the properties stored in the object are also updated
  3417. self.app_obj.object_changed.emit(obj)
  3418. # rebuild the object UI
  3419. obj.build_ui()
  3420. # change this only if the workspace is active
  3421. if self.defaults['global_workspace'] is True:
  3422. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3423. # adjust the grid values on the main toolbar
  3424. val_x = float(self.defaults['global_gridx']) * factor
  3425. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3426. current = self.collection.get_active()
  3427. if current is not None:
  3428. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3429. if not isinstance(current, GeometryObject):
  3430. current.to_form()
  3431. # replot all objects
  3432. self.plot_all()
  3433. # set the status labels to reflect the current FlatCAM units
  3434. self.set_screen_units(new_units)
  3435. # signal to the app that we changed the object properties and it should save the project
  3436. self.should_we_save = True
  3437. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3438. else:
  3439. # Undo toggling
  3440. self.toggle_units_ignore = True
  3441. if self.defaults['units'].upper() == 'MM':
  3442. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3443. else:
  3444. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3445. self.toggle_units_ignore = False
  3446. # store the grid values so they are not changed in the next step
  3447. val_x = float(self.defaults['global_gridx'])
  3448. val_y = float(self.defaults['global_gridy'])
  3449. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3450. self.preferencesUiManager.defaults_read_form()
  3451. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3452. # in self.defaults from the GUI elements but
  3453. # I don't want it for the grid values, so I update them here
  3454. self.defaults['global_gridx'] = val_x
  3455. self.defaults['global_gridy'] = val_y
  3456. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3457. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3458. def on_tab_rmb_click(self, checked):
  3459. self.ui.notebook.set_detachable(val=checked)
  3460. self.defaults["global_tabs_detachable"] = checked
  3461. self.ui.plot_tab_area.set_detachable(val=checked)
  3462. self.defaults["global_tabs_detachable"] = checked
  3463. def on_tab_setup_context_menu(self):
  3464. initial_checked = self.defaults["global_tabs_detachable"]
  3465. action_name = str(_("Detachable Tabs"))
  3466. action = QtWidgets.QAction(self)
  3467. action.setCheckable(True)
  3468. action.setText(action_name)
  3469. action.setChecked(initial_checked)
  3470. self.ui.notebook.tabBar.addAction(action)
  3471. self.ui.plot_tab_area.tabBar.addAction(action)
  3472. try:
  3473. action.triggered.disconnect()
  3474. except TypeError:
  3475. pass
  3476. action.triggered.connect(self.on_tab_rmb_click)
  3477. def on_deselect_all(self):
  3478. self.collection.set_all_inactive()
  3479. self.delete_selection_shape()
  3480. def on_workspace_modified(self):
  3481. # self.save_defaults(silent=True)
  3482. self.plotcanvas.delete_workspace()
  3483. self.preferencesUiManager.defaults_read_form()
  3484. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3485. def on_workspace(self):
  3486. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3487. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3488. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3489. else:
  3490. self.plotcanvas.delete_workspace()
  3491. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3492. self.preferencesUiManager.defaults_read_form()
  3493. # self.save_defaults(silent=True)
  3494. def on_workspace_toggle(self):
  3495. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3496. try:
  3497. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3498. except TypeError:
  3499. pass
  3500. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3501. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3502. self.on_workspace()
  3503. def on_cursor_type(self, val):
  3504. """
  3505. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3506. :return: None
  3507. """
  3508. self.app_cursor.enabled = False
  3509. if val == 'small':
  3510. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3511. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3512. self.app_cursor = self.plotcanvas.new_cursor()
  3513. else:
  3514. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3515. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3516. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3517. if self.ui.grid_snap_btn.isChecked():
  3518. self.app_cursor.enabled = True
  3519. else:
  3520. self.app_cursor.enabled = False
  3521. def on_tool_add_keypress(self):
  3522. # ## Current application units in Upper Case
  3523. self.units = self.defaults['units'].upper()
  3524. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3525. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3526. if notebook_widget_name == 'selected_tab':
  3527. if self.collection.get_active().kind == 'geometry':
  3528. # Tool add works for Geometry only if Advanced is True in Preferences
  3529. if self.defaults["global_app_level"] == 'a':
  3530. tool_add_popup = FCInputDialog(title="New Tool ...",
  3531. text='Enter a Tool Diameter:',
  3532. min=0.0000, max=99.9999, decimals=4)
  3533. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3534. val, ok = tool_add_popup.get_value()
  3535. if ok:
  3536. if float(val) == 0:
  3537. self.inform.emit('[WARNING_NOTCL] %s' %
  3538. _("Please enter a tool diameter with non-zero value, in Float format."))
  3539. return
  3540. self.collection.get_active().on_tool_add(dia=float(val))
  3541. else:
  3542. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3543. else:
  3544. msgbox = QtWidgets.QMessageBox()
  3545. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3546. "Go to Preferences -> General - Show Advanced Options."))
  3547. msgbox.setWindowTitle("Tool adding ...")
  3548. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3549. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3550. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3551. msgbox.setDefaultButton(bt_ok)
  3552. msgbox.exec_()
  3553. # work only if the notebook tab on focus is the Tools_Tab
  3554. if notebook_widget_name == 'tool_tab':
  3555. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3556. # and only if the tool is NCC Tool
  3557. if tool_widget == self.ncclear_tool.toolName:
  3558. self.ncclear_tool.on_add_tool_by_key()
  3559. # and only if the tool is Paint Area Tool
  3560. elif tool_widget == self.paint_tool.toolName:
  3561. self.paint_tool.on_add_tool_by_key()
  3562. # and only if the tool is Solder Paste Dispensing Tool
  3563. elif tool_widget == self.paste_tool.toolName:
  3564. self.paste_tool.on_add_tool_by_key()
  3565. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3566. # See description below.
  3567. def on_delete_keypress(self):
  3568. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3569. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3570. if notebook_widget_name == 'selected_tab':
  3571. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3572. self.collection.get_active().on_tool_delete()
  3573. # work only if the notebook tab on focus is the Tools_Tab
  3574. elif notebook_widget_name == 'tool_tab':
  3575. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3576. # and only if the tool is NCC Tool
  3577. if tool_widget == self.ncclear_tool.toolName:
  3578. self.ncclear_tool.on_tool_delete()
  3579. # and only if the tool is Paint Tool
  3580. elif tool_widget == self.paint_tool.toolName:
  3581. self.paint_tool.on_tool_delete()
  3582. # and only if the tool is Solder Paste Dispensing Tool
  3583. elif tool_widget == self.paste_tool.toolName:
  3584. self.paste_tool.on_tool_delete()
  3585. # and only if the tool is Isolation Tool
  3586. elif tool_widget == self.isolation_tool.toolName:
  3587. self.isolation_tool.on_tool_delete()
  3588. else:
  3589. self.on_delete()
  3590. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3591. # some screens you have to be careful where you hover with your mouse.
  3592. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3593. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3594. # Complicated, I know :)
  3595. def on_delete(self, force_deletion=False):
  3596. """
  3597. Delete the currently selected FlatCAMObjs.
  3598. :param force_deletion: used by Tcl command
  3599. :return: None
  3600. """
  3601. self.defaults.report_usage("on_delete()")
  3602. response = None
  3603. bt_ok = None
  3604. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3605. # a geometry object before we update it.
  3606. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3607. and self.grb_editor.editor_active is False:
  3608. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3609. msgbox = QtWidgets.QMessageBox()
  3610. msgbox.setWindowTitle(_("Delete objects"))
  3611. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3612. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3613. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3614. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3615. "the selected objects?"))
  3616. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3617. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3618. msgbox.setDefaultButton(bt_ok)
  3619. msgbox.exec_()
  3620. response = msgbox.clickedButton()
  3621. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3622. response = bt_ok
  3623. if response == bt_ok:
  3624. if self.collection.get_active():
  3625. self.log.debug("App.on_delete()")
  3626. for obj_active in self.collection.get_selected():
  3627. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3628. if obj_active.kind == 'gerber':
  3629. for el in obj_active.mark_shapes:
  3630. obj_active.mark_shapes[el].clear(update=True)
  3631. obj_active.mark_shapes[el].enabled = False
  3632. # obj_active.mark_shapes[el] = None
  3633. del el
  3634. elif obj_active.kind == 'cncjob':
  3635. try:
  3636. obj_active.text_col.enabled = False
  3637. del obj_active.text_col
  3638. obj_active.annotation.clear(update=True)
  3639. del obj_active.annotation
  3640. except AttributeError as e:
  3641. log.debug(
  3642. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3643. )
  3644. while self.collection.get_selected():
  3645. self.delete_first_selected()
  3646. # make sure that the selection shape is deleted, too
  3647. self.delete_selection_shape()
  3648. # if there are no longer objects delete also the exclusion areas shapes
  3649. if not self.collection.get_list():
  3650. self.exc_areas.clear_shapes()
  3651. self.inform.emit('%s...' % _("Object(s) deleted"))
  3652. else:
  3653. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3654. else:
  3655. self.inform.emit(_("Save the work in Editor and try again ..."))
  3656. def delete_first_selected(self):
  3657. # Keep this for later
  3658. try:
  3659. sel_obj = self.collection.get_active()
  3660. name = sel_obj.options["name"]
  3661. isPlotted = sel_obj.options["plot"]
  3662. except AttributeError:
  3663. self.log.debug("Nothing selected for deletion")
  3664. return
  3665. if self.is_legacy is True:
  3666. # Remove plot only if the object was plotted otherwise delaxes will fail
  3667. if isPlotted:
  3668. try:
  3669. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3670. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3671. except Exception as e:
  3672. log.debug("App.delete_first_selected() --> %s" % str(e))
  3673. self.plotcanvas.auto_adjust_axes()
  3674. # Remove from dictionary
  3675. self.collection.delete_active()
  3676. # Clear form
  3677. self.setup_component_editor()
  3678. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3679. def on_set_origin(self):
  3680. """
  3681. Set the origin to the left mouse click position
  3682. :return: None
  3683. """
  3684. # display the message for the user
  3685. # and ask him to click on the desired position
  3686. self.defaults.report_usage("on_set_origin()")
  3687. def origin_replot():
  3688. def worker_task():
  3689. with self.proc_container.new('%s...' % _("Plotting")):
  3690. for obj in self.collection.get_list():
  3691. obj.plot()
  3692. self.plotcanvas.fit_view()
  3693. if self.is_legacy:
  3694. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3695. else:
  3696. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3697. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3698. self.inform.emit(_('Click to set the origin ...'))
  3699. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3700. # first disconnect it as it may have been used by something else
  3701. try:
  3702. self.replot_signal.disconnect()
  3703. except TypeError:
  3704. pass
  3705. self.replot_signal[list].connect(origin_replot)
  3706. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3707. """
  3708. :param event:
  3709. :param location:
  3710. :param noplot:
  3711. :param use_thread:
  3712. :return:
  3713. """
  3714. noplot_sig = noplot
  3715. def worker_task():
  3716. with self.proc_container.new(_("Setting Origin...")):
  3717. obj_list = self.collection.get_list()
  3718. for obj in obj_list:
  3719. obj.offset((x, y))
  3720. self.app_obj.object_changed.emit(obj)
  3721. # Update the object bounding box options
  3722. a, b, c, d = obj.bounds()
  3723. obj.options['xmin'] = a
  3724. obj.options['ymin'] = b
  3725. obj.options['xmax'] = c
  3726. obj.options['ymax'] = d
  3727. self.inform.emit('[success] %s...' % _('Origin set'))
  3728. for obj in obj_list:
  3729. out_name = obj.options["name"]
  3730. if obj.kind == 'gerber':
  3731. obj.source_file = self.export_gerber(
  3732. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3733. elif obj.kind == 'excellon':
  3734. obj.source_file = self.export_excellon(
  3735. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3736. if noplot_sig is False:
  3737. self.replot_signal.emit([])
  3738. if location is not None:
  3739. if len(location) != 2:
  3740. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3741. return 'fail'
  3742. x, y = location
  3743. if use_thread is True:
  3744. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3745. else:
  3746. worker_task()
  3747. self.should_we_save = True
  3748. return
  3749. if event is not None and event.button == 1:
  3750. if self.is_legacy is False:
  3751. event_pos = event.pos
  3752. else:
  3753. event_pos = (event.xdata, event.ydata)
  3754. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3755. if self.grid_status():
  3756. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3757. else:
  3758. pos = pos_canvas
  3759. x = 0 - pos[0]
  3760. y = 0 - pos[1]
  3761. if use_thread is True:
  3762. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3763. else:
  3764. worker_task()
  3765. self.should_we_save = True
  3766. def on_move2origin(self, use_thread=True):
  3767. """
  3768. Move selected objects to origin.
  3769. :param use_thread: Control if to use threaded operation. Boolean.
  3770. :return:
  3771. """
  3772. def worker_task():
  3773. with self.proc_container.new(_("Moving to Origin...")):
  3774. obj_list = self.collection.get_selected()
  3775. if not obj_list:
  3776. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3777. return
  3778. xminlist = []
  3779. yminlist = []
  3780. # first get a bounding box to fit all
  3781. for obj in obj_list:
  3782. xmin, ymin, xmax, ymax = obj.bounds()
  3783. xminlist.append(xmin)
  3784. yminlist.append(ymin)
  3785. # get the minimum x,y for all objects selected
  3786. x = min(xminlist)
  3787. y = min(yminlist)
  3788. for obj in obj_list:
  3789. obj.offset((-x, -y))
  3790. self.app_obj.object_changed.emit(obj)
  3791. # Update the object bounding box options
  3792. a, b, c, d = obj.bounds()
  3793. obj.options['xmin'] = a
  3794. obj.options['ymin'] = b
  3795. obj.options['xmax'] = c
  3796. obj.options['ymax'] = d
  3797. for obj in obj_list:
  3798. obj.plot()
  3799. for obj in obj_list:
  3800. out_name = obj.options["name"]
  3801. if obj.kind == 'gerber':
  3802. obj.source_file = self.export_gerber(
  3803. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3804. elif obj.kind == 'excellon':
  3805. obj.source_file = self.export_excellon(
  3806. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3807. self.inform.emit('[success] %s...' % _('Origin set'))
  3808. if use_thread is True:
  3809. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3810. else:
  3811. worker_task()
  3812. self.should_we_save = True
  3813. def on_jump_to(self, custom_location=None, fit_center=True):
  3814. """
  3815. Jump to a location by setting the mouse cursor location.
  3816. :param custom_location: Jump to a specified point. (x, y) tuple.
  3817. :param fit_center: If to fit view. Boolean.
  3818. :return:
  3819. """
  3820. self.defaults.report_usage("on_jump_to()")
  3821. if not custom_location:
  3822. dia_box_location = None
  3823. try:
  3824. dia_box_location = eval(self.clipboard.text())
  3825. except Exception:
  3826. pass
  3827. if type(dia_box_location) == tuple:
  3828. dia_box_location = str(dia_box_location)
  3829. else:
  3830. dia_box_location = None
  3831. # dia_box = Dialog_box(title=_("Jump to ..."),
  3832. # label=_("Enter the coordinates in format X,Y:"),
  3833. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3834. # initial_text=dia_box_location)
  3835. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3836. label=_("Enter the coordinates in format X,Y:"),
  3837. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3838. initial_text=dia_box_location,
  3839. reference=self.defaults['global_jump_ref'])
  3840. if dia_box.ok is True:
  3841. try:
  3842. location = eval(dia_box.location)
  3843. if not isinstance(location, tuple):
  3844. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3845. return
  3846. if dia_box.reference == 'rel':
  3847. rel_x = self.mouse[0] + location[0]
  3848. rel_y = self.mouse[1] + location[1]
  3849. location = (rel_x, rel_y)
  3850. self.defaults['global_jump_ref'] = dia_box.reference
  3851. except Exception:
  3852. return
  3853. else:
  3854. return
  3855. else:
  3856. location = custom_location
  3857. self.jump_signal.emit(location)
  3858. if fit_center:
  3859. self.plotcanvas.fit_center(loc=location)
  3860. cursor = QtGui.QCursor()
  3861. if self.is_legacy is False:
  3862. # I don't know where those differences come from but they are constant for the current
  3863. # execution of the application and they are multiples of a value around 0.0263mm.
  3864. # In a random way sometimes they are more sometimes they are less
  3865. # if units == 'MM':
  3866. # cal_factor = 0.0263
  3867. # else:
  3868. # cal_factor = 0.0263 / 25.4
  3869. cal_location = (location[0], location[1])
  3870. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3871. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3872. j_pos = (
  3873. int(canvas_origin.x() + round(jump_loc[0])),
  3874. int(canvas_origin.y() + round(jump_loc[1]))
  3875. )
  3876. cursor.setPos(j_pos[0], j_pos[1])
  3877. else:
  3878. # find the canvas origin which is in the top left corner
  3879. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3880. # determine the coordinates for the lowest left point of the canvas
  3881. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3882. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3883. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3884. # canvas) and the point (width, height) is in the top-right location
  3885. loc = self.plotcanvas.axes.transData.transform_point(location)
  3886. j_pos = (
  3887. int(x0 + loc[0]),
  3888. int(y0 - loc[1])
  3889. )
  3890. cursor.setPos(j_pos[0], j_pos[1])
  3891. self.plotcanvas.mouse = [location[0], location[1]]
  3892. if self.defaults["global_cursor_color_enabled"] is True:
  3893. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3894. else:
  3895. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3896. if self.grid_status():
  3897. # Update cursor
  3898. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3899. symbol='++', edge_color=self.cursor_color_3D,
  3900. edge_width=self.defaults["global_cursor_width"],
  3901. size=self.defaults["global_cursor_size"])
  3902. # Set the relative position label
  3903. dx = location[0] - float(self.rel_point1[0])
  3904. dy = location[1] - float(self.rel_point1[1])
  3905. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3906. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3907. # # Set the position label
  3908. #
  3909. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3910. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3911. units = self.defaults["units"].lower()
  3912. self.plotcanvas.text_hud.text = \
  3913. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3914. dx, units, dy, units, location[0], units, location[1], units)
  3915. self.inform.emit('[success] %s' % _("Done."))
  3916. return location
  3917. def on_locate(self, obj, fit_center=True):
  3918. """
  3919. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3920. :param obj: The object on which to locate certain points
  3921. :param fit_center: If to fit view. Boolean.
  3922. :return: A point location. (x, y) tuple.
  3923. """
  3924. self.defaults.report_usage("on_locate()")
  3925. if obj is None:
  3926. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3927. return 'fail'
  3928. class DialogBoxChoice(QtWidgets.QDialog):
  3929. def __init__(self, title=None, icon=None, choice='bl'):
  3930. """
  3931. :param title: string with the window title
  3932. """
  3933. super(DialogBoxChoice, self).__init__()
  3934. self.ok = False
  3935. self.setWindowIcon(icon)
  3936. self.setWindowTitle(str(title))
  3937. self.form = QtWidgets.QFormLayout(self)
  3938. self.ref_radio = RadioSet([
  3939. {"label": _("Bottom-Left"), "value": "bl"},
  3940. {"label": _("Top-Left"), "value": "tl"},
  3941. {"label": _("Bottom-Right"), "value": "br"},
  3942. {"label": _("Top-Right"), "value": "tr"},
  3943. {"label": _("Center"), "value": "c"}
  3944. ], orientation='vertical', stretch=False)
  3945. self.ref_radio.set_value(choice)
  3946. self.form.addRow(self.ref_radio)
  3947. self.button_box = QtWidgets.QDialogButtonBox(
  3948. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3949. Qt.Horizontal, parent=self)
  3950. self.form.addRow(self.button_box)
  3951. self.button_box.accepted.connect(self.accept)
  3952. self.button_box.rejected.connect(self.reject)
  3953. if self.exec_() == QtWidgets.QDialog.Accepted:
  3954. self.ok = True
  3955. self.location_point = self.ref_radio.get_value()
  3956. else:
  3957. self.ok = False
  3958. self.location_point = None
  3959. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3960. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3961. choice=self.defaults['global_locate_pt'])
  3962. if dia_box.ok is True:
  3963. try:
  3964. location_point = dia_box.location_point
  3965. self.defaults['global_locate_pt'] = dia_box.location_point
  3966. except Exception:
  3967. return
  3968. else:
  3969. return
  3970. loc_b = obj.bounds()
  3971. if location_point == 'bl':
  3972. location = (loc_b[0], loc_b[1])
  3973. elif location_point == 'tl':
  3974. location = (loc_b[0], loc_b[3])
  3975. elif location_point == 'br':
  3976. location = (loc_b[2], loc_b[1])
  3977. elif location_point == 'tr':
  3978. location = (loc_b[2], loc_b[3])
  3979. else:
  3980. # center
  3981. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3982. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3983. location = (cx, cy)
  3984. self.locate_signal.emit(location, location_point)
  3985. if fit_center:
  3986. self.plotcanvas.fit_center(loc=location)
  3987. cursor = QtGui.QCursor()
  3988. if self.is_legacy is False:
  3989. # I don't know where those differences come from but they are constant for the current
  3990. # execution of the application and they are multiples of a value around 0.0263mm.
  3991. # In a random way sometimes they are more sometimes they are less
  3992. # if units == 'MM':
  3993. # cal_factor = 0.0263
  3994. # else:
  3995. # cal_factor = 0.0263 / 25.4
  3996. cal_location = (location[0], location[1])
  3997. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3998. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3999. j_pos = (
  4000. int(canvas_origin.x() + round(jump_loc[0])),
  4001. int(canvas_origin.y() + round(jump_loc[1]))
  4002. )
  4003. cursor.setPos(j_pos[0], j_pos[1])
  4004. else:
  4005. # find the canvas origin which is in the top left corner
  4006. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4007. # determine the coordinates for the lowest left point of the canvas
  4008. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4009. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4010. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4011. # canvas) and the point (width, height) is in the top-right location
  4012. loc = self.plotcanvas.axes.transData.transform_point(location)
  4013. j_pos = (
  4014. int(x0 + loc[0]),
  4015. int(y0 - loc[1])
  4016. )
  4017. cursor.setPos(j_pos[0], j_pos[1])
  4018. self.plotcanvas.mouse = [location[0], location[1]]
  4019. if self.defaults["global_cursor_color_enabled"] is True:
  4020. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4021. else:
  4022. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4023. if self.grid_status():
  4024. # Update cursor
  4025. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4026. symbol='++', edge_color=self.cursor_color_3D,
  4027. edge_width=self.defaults["global_cursor_width"],
  4028. size=self.defaults["global_cursor_size"])
  4029. # Set the relative position label
  4030. self.dx = location[0] - float(self.rel_point1[0])
  4031. self.dy = location[1] - float(self.rel_point1[1])
  4032. # Set the position label
  4033. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4034. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4035. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4036. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4037. units = self.defaults["units"].lower()
  4038. self.plotcanvas.text_hud.text = \
  4039. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4040. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4041. self.inform.emit('[success] %s' % _("Done."))
  4042. return location
  4043. def on_copy_command(self):
  4044. """
  4045. Will copy a selection of objects, creating new objects.
  4046. :return:
  4047. """
  4048. self.defaults.report_usage("on_copy_command()")
  4049. def initialize(obj_init, app):
  4050. """
  4051. :param obj_init: the new object
  4052. :type obj_init: class
  4053. :param app: An instance of the App class
  4054. :type app: App
  4055. :return: None
  4056. :rtype:
  4057. """
  4058. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4059. try:
  4060. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4061. except AttributeError:
  4062. pass
  4063. try:
  4064. obj_init.apertures = deepcopy(obj.apertures)
  4065. except AttributeError:
  4066. pass
  4067. try:
  4068. if obj.tools:
  4069. obj_init.tools = deepcopy(obj.tools)
  4070. except Exception as err:
  4071. log.debug("App.on_copy_command() --> %s" % str(err))
  4072. try:
  4073. obj_init.source_file = deepcopy(obj.source_file)
  4074. except (AttributeError, TypeError):
  4075. pass
  4076. def initialize_excellon(obj_init, app):
  4077. obj_init.source_file = deepcopy(obj.source_file)
  4078. obj_init.tools = deepcopy(obj.tools)
  4079. # drills are offset, so they need to be deep copied
  4080. obj_init.drills = deepcopy(obj.drills)
  4081. # slots are offset, so they need to be deep copied
  4082. obj_init.slots = deepcopy(obj.slots)
  4083. obj_init.create_geometry()
  4084. def initialize_script(obj_init, app_obj):
  4085. obj_init.source_file = deepcopy(obj.source_file)
  4086. def initialize_document(obj_init, app_obj):
  4087. obj_init.source_file = deepcopy(obj.source_file)
  4088. for obj in self.collection.get_selected():
  4089. obj_name = obj.options["name"]
  4090. try:
  4091. if isinstance(obj, ExcellonObject):
  4092. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4093. elif isinstance(obj, GerberObject):
  4094. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4095. elif isinstance(obj, GeometryObject):
  4096. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4097. elif isinstance(obj, ScriptObject):
  4098. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4099. elif isinstance(obj, DocumentObject):
  4100. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4101. except Exception as e:
  4102. return "Operation failed: %s" % str(e)
  4103. def on_copy_object2(self, custom_name):
  4104. def initialize_geometry(obj_init, app):
  4105. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4106. try:
  4107. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4108. except AttributeError:
  4109. pass
  4110. try:
  4111. obj_init.apertures = deepcopy(obj.apertures)
  4112. except AttributeError:
  4113. pass
  4114. try:
  4115. if obj.tools:
  4116. obj_init.tools = deepcopy(obj.tools)
  4117. except Exception as ee:
  4118. log.debug("on_copy_object2() --> %s" % str(ee))
  4119. def initialize_gerber(obj_init, app):
  4120. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4121. obj_init.apertures = deepcopy(obj.apertures)
  4122. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4123. def initialize_excellon(obj_init, app):
  4124. obj_init.tools = deepcopy(obj.tools)
  4125. # drills are offset, so they need to be deep copied
  4126. obj_init.drills = deepcopy(obj.drills)
  4127. # slots are offset, so they need to be deep copied
  4128. obj_init.slots = deepcopy(obj.slots)
  4129. obj_init.create_geometry()
  4130. for obj in self.collection.get_selected():
  4131. obj_name = obj.options["name"]
  4132. try:
  4133. if isinstance(obj, ExcellonObject):
  4134. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4135. elif isinstance(obj, GerberObject):
  4136. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4137. elif isinstance(obj, GeometryObject):
  4138. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4139. except Exception as er:
  4140. return "Operation failed: %s" % str(er)
  4141. def on_rename_object(self, text):
  4142. """
  4143. Will rename an object.
  4144. :param text: New name for the object.
  4145. :return:
  4146. """
  4147. self.defaults.report_usage("on_rename_object()")
  4148. named_obj = self.collection.get_active()
  4149. for obj in named_obj:
  4150. if obj is list:
  4151. self.on_rename_object(text)
  4152. else:
  4153. try:
  4154. obj.options['name'] = text
  4155. except Exception as e:
  4156. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4157. def convert_any2geo(self):
  4158. """
  4159. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4160. :return:
  4161. """
  4162. self.defaults.report_usage("convert_any2geo()")
  4163. def initialize(obj_init, app):
  4164. obj_init.solid_geometry = obj.solid_geometry
  4165. try:
  4166. obj_init.follow_geometry = obj.follow_geometry
  4167. except AttributeError:
  4168. pass
  4169. try:
  4170. obj_init.apertures = obj.apertures
  4171. except AttributeError:
  4172. pass
  4173. try:
  4174. if obj.tools:
  4175. obj_init.tools = obj.tools
  4176. except AttributeError:
  4177. pass
  4178. def initialize_excellon(obj_init, app):
  4179. # objs = self.collection.get_selected()
  4180. # GeometryObject.merge(objs, obj)
  4181. solid_geo = []
  4182. for tool in obj.tools:
  4183. for geo in obj.tools[tool]['solid_geometry']:
  4184. solid_geo.append(geo)
  4185. obj_init.solid_geometry = deepcopy(solid_geo)
  4186. if not self.collection.get_selected():
  4187. log.warning("App.convert_any2geo --> No object selected")
  4188. self.inform.emit('[WARNING_NOTCL] %s' %
  4189. _("No object is selected. Select an object and try again."))
  4190. return
  4191. for obj in self.collection.get_selected():
  4192. obj_name = obj.options["name"]
  4193. try:
  4194. if isinstance(obj, ExcellonObject):
  4195. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4196. else:
  4197. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4198. except Exception as e:
  4199. return "Operation failed: %s" % str(e)
  4200. def convert_any2gerber(self):
  4201. """
  4202. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4203. :return:
  4204. """
  4205. self.defaults.report_usage("convert_any2gerber()")
  4206. def initialize_geometry(obj_init, app):
  4207. apertures = {}
  4208. apid = 0
  4209. apertures[str(apid)] = {}
  4210. apertures[str(apid)]['geometry'] = []
  4211. for obj_orig in obj.solid_geometry:
  4212. new_elem = {}
  4213. new_elem['solid'] = obj_orig
  4214. try:
  4215. new_elem['follow'] = obj_orig.exterior
  4216. except AttributeError:
  4217. pass
  4218. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4219. apertures[str(apid)]['size'] = 0.0
  4220. apertures[str(apid)]['type'] = 'C'
  4221. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4222. obj_init.apertures = deepcopy(apertures)
  4223. def initialize_excellon(obj_init, app):
  4224. apertures = {}
  4225. apid = 10
  4226. for tool in obj.tools:
  4227. apertures[str(apid)] = {}
  4228. apertures[str(apid)]['geometry'] = []
  4229. for geo in obj.tools[tool]['solid_geometry']:
  4230. new_el = {}
  4231. new_el['solid'] = geo
  4232. new_el['follow'] = geo.exterior
  4233. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4234. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4235. apertures[str(apid)]['type'] = 'C'
  4236. apid += 1
  4237. # create solid_geometry
  4238. solid_geometry = []
  4239. for apid in apertures:
  4240. for geo_el in apertures[apid]['geometry']:
  4241. solid_geometry.append(geo_el['solid'])
  4242. solid_geometry = MultiPolygon(solid_geometry)
  4243. solid_geometry = solid_geometry.buffer(0.0000001)
  4244. obj_init.solid_geometry = deepcopy(solid_geometry)
  4245. obj_init.apertures = deepcopy(apertures)
  4246. # clear the working objects (perhaps not necessary due of Python GC)
  4247. apertures.clear()
  4248. if not self.collection.get_selected():
  4249. log.warning("App.convert_any2gerber --> No object selected")
  4250. self.inform.emit('[WARNING_NOTCL] %s' %
  4251. _("No object is selected. Select an object and try again."))
  4252. return
  4253. for obj in self.collection.get_selected():
  4254. obj_name = obj.options["name"]
  4255. try:
  4256. if isinstance(obj, ExcellonObject):
  4257. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4258. elif isinstance(obj, GeometryObject):
  4259. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4260. else:
  4261. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4262. except Exception as e:
  4263. return "Operation failed: %s" % str(e)
  4264. def abort_all_tasks(self):
  4265. """
  4266. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4267. on the first possible occasion.
  4268. :return:
  4269. """
  4270. if self.abort_flag is False:
  4271. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4272. self.abort_flag = True
  4273. self.cleanup.emit()
  4274. def app_is_idle(self):
  4275. if self.abort_flag:
  4276. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4277. self.abort_flag = False
  4278. def on_selectall(self):
  4279. """
  4280. Will draw a selection box shape around the selected objects.
  4281. :return:
  4282. """
  4283. self.defaults.report_usage("on_selectall()")
  4284. # delete the possible selection box around a possible selected object
  4285. self.delete_selection_shape()
  4286. for name in self.collection.get_names():
  4287. self.collection.set_active(name)
  4288. curr_sel_obj = self.collection.get_by_name(name)
  4289. # create the selection box around the selected object
  4290. if self.defaults['global_selection_shape'] is True:
  4291. self.draw_selection_shape(curr_sel_obj)
  4292. def on_toggle_preferences(self):
  4293. pref_open = False
  4294. for idx in range(self.ui.plot_tab_area.count()):
  4295. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4296. pref_open = True
  4297. if pref_open:
  4298. for idx in range(self.ui.plot_tab_area.count()):
  4299. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4300. self.ui.plot_tab_area.removeTab(idx)
  4301. break
  4302. self.ui.pref_status_label.setStyleSheet("")
  4303. else:
  4304. self.on_preferences()
  4305. def on_preferences(self):
  4306. """
  4307. Adds the Preferences in a Tab in Plot Area
  4308. :return:
  4309. """
  4310. # add the tab if it was closed
  4311. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4312. # delete the absolute and relative position and messages in the infobar
  4313. self.ui.position_label.setText("")
  4314. # self.ui.rel_position_label.setText("")
  4315. # Switch plot_area to preferences page
  4316. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4317. # self.ui.show()
  4318. self.ui.pref_status_label.setStyleSheet("""
  4319. QLabel
  4320. {
  4321. color: black;
  4322. background-color: lightseagreen;
  4323. }
  4324. """
  4325. )
  4326. # detect changes in the preferences
  4327. for idx in range(self.ui.pref_tab_area.count()):
  4328. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4329. try:
  4330. try:
  4331. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4332. except (TypeError, AttributeError):
  4333. pass
  4334. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4335. except AttributeError:
  4336. pass
  4337. try:
  4338. try:
  4339. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4340. except (TypeError, AttributeError):
  4341. pass
  4342. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4343. except AttributeError:
  4344. pass
  4345. try:
  4346. try:
  4347. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4348. except (TypeError, AttributeError):
  4349. pass
  4350. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4351. except AttributeError:
  4352. pass
  4353. try:
  4354. try:
  4355. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4356. except (TypeError, AttributeError):
  4357. pass
  4358. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4359. except AttributeError:
  4360. pass
  4361. try:
  4362. try:
  4363. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4364. except (TypeError, AttributeError):
  4365. pass
  4366. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4367. except AttributeError:
  4368. pass
  4369. def on_tools_database(self, source='app'):
  4370. """
  4371. Adds the Tools Database in a Tab in Plot Area.
  4372. :return:
  4373. """
  4374. for idx in range(self.ui.plot_tab_area.count()):
  4375. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4376. # there can be only one instance of Tools Database at one time
  4377. return
  4378. if source == 'app':
  4379. self.tools_db_tab = ToolsDB2(
  4380. app=self,
  4381. parent=self.ui,
  4382. callback_on_edited=self.on_tools_db_edited,
  4383. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4384. )
  4385. elif source == 'ncc':
  4386. self.tools_db_tab = ToolsDB2(
  4387. app=self,
  4388. parent=self.ui,
  4389. callback_on_edited=self.on_tools_db_edited,
  4390. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4391. )
  4392. elif source == 'paint':
  4393. self.tools_db_tab = ToolsDB2(
  4394. app=self,
  4395. parent=self.ui,
  4396. callback_on_edited=self.on_tools_db_edited,
  4397. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4398. )
  4399. elif source == 'iso':
  4400. self.tools_db_tab = ToolsDB2(
  4401. app=self,
  4402. parent=self.ui,
  4403. callback_on_edited=self.on_tools_db_edited,
  4404. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4405. )
  4406. # add the tab if it was closed
  4407. try:
  4408. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4409. self.tools_db_tab.setObjectName("database_tab")
  4410. except Exception as e:
  4411. log.debug("App.on_tools_database() --> %s" % str(e))
  4412. return
  4413. # delete the absolute and relative position and messages in the infobar
  4414. self.ui.position_label.setText("")
  4415. # self.ui.rel_position_label.setText("")
  4416. # Switch plot_area to preferences page
  4417. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4418. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4419. self.tools_db_tab.ui_connect()
  4420. def on_tools_db_edited(self):
  4421. """
  4422. Executed whenever a tool is edited in Tools Database.
  4423. Will color the text of the Tools Database tab to Red color.
  4424. :return:
  4425. """
  4426. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4427. for idx in range(self.ui.plot_tab_area.count()):
  4428. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4429. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4430. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4431. self.tools_db_changed_flag = True
  4432. def on_geometry_tool_add_from_db_executed(self, tool):
  4433. """
  4434. Here add the tool from DB in the selected geometry object.
  4435. :return:
  4436. """
  4437. tool_from_db = deepcopy(tool)
  4438. obj = self.collection.get_active()
  4439. if obj.kind == 'geometry':
  4440. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4441. # close the tab and delete it
  4442. for idx in range(self.ui.plot_tab_area.count()):
  4443. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4444. wdg = self.ui.plot_tab_area.widget(idx)
  4445. wdg.deleteLater()
  4446. self.ui.plot_tab_area.removeTab(idx)
  4447. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4448. elif obj.kind == 'gerber':
  4449. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4450. # close the tab and delete it
  4451. for idx in range(self.ui.plot_tab_area.count()):
  4452. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4453. wdg = self.ui.plot_tab_area.widget(idx)
  4454. wdg.deleteLater()
  4455. self.ui.plot_tab_area.removeTab(idx)
  4456. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4457. else:
  4458. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4459. def on_plot_area_tab_closed(self, tab_obj_name):
  4460. """
  4461. Executed whenever a QTab is closed in the Plot Area.
  4462. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4463. :return:
  4464. """
  4465. if tab_obj_name == "preferences_tab":
  4466. self.preferencesUiManager.on_close_preferences_tab()
  4467. elif tab_obj_name == "database_tab":
  4468. # disconnect the signals from the table widget in tab
  4469. self.tools_db_tab.ui_disconnect()
  4470. if self.tools_db_changed_flag is True:
  4471. msgbox = QtWidgets.QMessageBox()
  4472. msgbox.setText(_("One or more Tools are edited.\n"
  4473. "Do you want to update the Tools Database?"))
  4474. msgbox.setWindowTitle(_("Save Tools Database"))
  4475. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4476. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4477. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4478. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4479. msgbox.setDefaultButton(bt_yes)
  4480. msgbox.exec_()
  4481. response = msgbox.clickedButton()
  4482. if response == bt_yes:
  4483. self.tools_db_tab.on_save_tools_db()
  4484. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4485. else:
  4486. self.tools_db_changed_flag = False
  4487. self.inform.emit('')
  4488. return
  4489. self.tools_db_tab.deleteLater()
  4490. elif tab_obj_name == "text_editor_tab":
  4491. self.toggle_codeeditor = False
  4492. elif tab_obj_name == "bookmarks_tab":
  4493. self.book_dialog_tab.rebuild_actions()
  4494. self.book_dialog_tab.deleteLater()
  4495. else:
  4496. return
  4497. # def on_plotarea_tab_closed(self, tab_idx):
  4498. # """
  4499. #
  4500. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4501. # :return:
  4502. # """
  4503. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4504. #
  4505. # if widget is not None:
  4506. # widget.deleteLater()
  4507. # self.ui.plot_tab_area.removeTab(tab_idx)
  4508. def on_flipy(self):
  4509. """
  4510. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4511. :return:
  4512. """
  4513. self.defaults.report_usage("on_flipy()")
  4514. obj_list = self.collection.get_selected()
  4515. xminlist = []
  4516. yminlist = []
  4517. xmaxlist = []
  4518. ymaxlist = []
  4519. if not obj_list:
  4520. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4521. else:
  4522. try:
  4523. # first get a bounding box to fit all
  4524. for obj in obj_list:
  4525. xmin, ymin, xmax, ymax = obj.bounds()
  4526. xminlist.append(xmin)
  4527. yminlist.append(ymin)
  4528. xmaxlist.append(xmax)
  4529. ymaxlist.append(ymax)
  4530. # get the minimum x,y and maximum x,y for all objects selected
  4531. xminimal = min(xminlist)
  4532. yminimal = min(yminlist)
  4533. xmaximal = max(xmaxlist)
  4534. ymaximal = max(ymaxlist)
  4535. px = 0.5 * (xminimal + xmaximal)
  4536. py = 0.5 * (yminimal + ymaximal)
  4537. # execute mirroring
  4538. for obj in obj_list:
  4539. obj.mirror('X', [px, py])
  4540. obj.plot()
  4541. self.app_obj.object_changed.emit(obj)
  4542. self.inform.emit('[success] %s' %
  4543. _("Flip on Y axis done."))
  4544. except Exception as e:
  4545. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4546. return
  4547. def on_flipx(self):
  4548. """
  4549. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4550. :return:
  4551. """
  4552. self.defaults.report_usage("on_flipx()")
  4553. obj_list = self.collection.get_selected()
  4554. xminlist = []
  4555. yminlist = []
  4556. xmaxlist = []
  4557. ymaxlist = []
  4558. if not obj_list:
  4559. self.inform.emit('[WARNING_NOTCL] %s' %
  4560. _("No object selected to Flip on X axis."))
  4561. else:
  4562. try:
  4563. # first get a bounding box to fit all
  4564. for obj in obj_list:
  4565. xmin, ymin, xmax, ymax = obj.bounds()
  4566. xminlist.append(xmin)
  4567. yminlist.append(ymin)
  4568. xmaxlist.append(xmax)
  4569. ymaxlist.append(ymax)
  4570. # get the minimum x,y and maximum x,y for all objects selected
  4571. xminimal = min(xminlist)
  4572. yminimal = min(yminlist)
  4573. xmaximal = max(xmaxlist)
  4574. ymaximal = max(ymaxlist)
  4575. px = 0.5 * (xminimal + xmaximal)
  4576. py = 0.5 * (yminimal + ymaximal)
  4577. # execute mirroring
  4578. for obj in obj_list:
  4579. obj.mirror('Y', [px, py])
  4580. obj.plot()
  4581. self.app_obj.object_changed.emit(obj)
  4582. self.inform.emit('[success] %s' %
  4583. _("Flip on X axis done."))
  4584. except Exception as e:
  4585. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4586. return
  4587. def on_rotate(self, silent=False, preset=None):
  4588. """
  4589. Executed when Options -> Rotate Selection menu entry is clicked.
  4590. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4591. :param preset: A value to be used as predefined angle for rotation.
  4592. :return:
  4593. """
  4594. self.defaults.report_usage("on_rotate()")
  4595. obj_list = self.collection.get_selected()
  4596. xminlist = []
  4597. yminlist = []
  4598. xmaxlist = []
  4599. ymaxlist = []
  4600. if not obj_list:
  4601. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4602. else:
  4603. if silent is False:
  4604. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4605. min=-360, max=360, decimals=4,
  4606. init_val=float(self.defaults['tools_transform_rotate']))
  4607. num, ok = rotatebox.get_value()
  4608. else:
  4609. num = preset
  4610. ok = True
  4611. if ok:
  4612. try:
  4613. # first get a bounding box to fit all
  4614. for obj in obj_list:
  4615. xmin, ymin, xmax, ymax = obj.bounds()
  4616. xminlist.append(xmin)
  4617. yminlist.append(ymin)
  4618. xmaxlist.append(xmax)
  4619. ymaxlist.append(ymax)
  4620. # get the minimum x,y and maximum x,y for all objects selected
  4621. xminimal = min(xminlist)
  4622. yminimal = min(yminlist)
  4623. xmaximal = max(xmaxlist)
  4624. ymaximal = max(ymaxlist)
  4625. px = 0.5 * (xminimal + xmaximal)
  4626. py = 0.5 * (yminimal + ymaximal)
  4627. for sel_obj in obj_list:
  4628. sel_obj.rotate(-float(num), point=(px, py))
  4629. sel_obj.plot()
  4630. self.app_obj.object_changed.emit(sel_obj)
  4631. self.inform.emit('[success] %s' % _("Rotation done."))
  4632. except Exception as e:
  4633. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4634. return
  4635. def on_skewx(self):
  4636. """
  4637. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4638. :return:
  4639. """
  4640. self.defaults.report_usage("on_skewx()")
  4641. obj_list = self.collection.get_selected()
  4642. xminlist = []
  4643. yminlist = []
  4644. if not obj_list:
  4645. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4646. else:
  4647. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4648. min=-360, max=360, decimals=4,
  4649. init_val=float(self.defaults['tools_transform_skew_x']))
  4650. num, ok = skewxbox.get_value()
  4651. if ok:
  4652. # first get a bounding box to fit all
  4653. for obj in obj_list:
  4654. xmin, ymin, xmax, ymax = obj.bounds()
  4655. xminlist.append(xmin)
  4656. yminlist.append(ymin)
  4657. # get the minimum x,y and maximum x,y for all objects selected
  4658. xminimal = min(xminlist)
  4659. yminimal = min(yminlist)
  4660. for obj in obj_list:
  4661. obj.skew(num, 0, point=(xminimal, yminimal))
  4662. obj.plot()
  4663. self.app_obj.object_changed.emit(obj)
  4664. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4665. def on_skewy(self):
  4666. """
  4667. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4668. :return:
  4669. """
  4670. self.defaults.report_usage("on_skewy()")
  4671. obj_list = self.collection.get_selected()
  4672. xminlist = []
  4673. yminlist = []
  4674. if not obj_list:
  4675. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4676. else:
  4677. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4678. min=-360, max=360, decimals=4,
  4679. init_val=float(self.defaults['tools_transform_skew_y']))
  4680. num, ok = skewybox.get_value()
  4681. if ok:
  4682. # first get a bounding box to fit all
  4683. for obj in obj_list:
  4684. xmin, ymin, xmax, ymax = obj.bounds()
  4685. xminlist.append(xmin)
  4686. yminlist.append(ymin)
  4687. # get the minimum x,y and maximum x,y for all objects selected
  4688. xminimal = min(xminlist)
  4689. yminimal = min(yminlist)
  4690. for obj in obj_list:
  4691. obj.skew(0, num, point=(xminimal, yminimal))
  4692. obj.plot()
  4693. self.app_obj.object_changed.emit(obj)
  4694. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4695. def on_plots_updated(self):
  4696. """
  4697. Callback used to report when the plots have changed.
  4698. Adjust axes and zooms to fit.
  4699. :return: None
  4700. """
  4701. if self.is_legacy is False:
  4702. self.plotcanvas.update()
  4703. else:
  4704. self.plotcanvas.auto_adjust_axes()
  4705. self.on_zoom_fit()
  4706. self.collection.update_view()
  4707. # self.inform.emit(_("Plots updated ..."))
  4708. def on_toolbar_replot(self):
  4709. """
  4710. Callback for toolbar button. Re-plots all objects.
  4711. :return: None
  4712. """
  4713. self.log.debug("on_toolbar_replot()")
  4714. try:
  4715. self.collection.get_active().read_form()
  4716. except AttributeError:
  4717. self.log.debug("on_toolbar_replot(): AttributeError")
  4718. pass
  4719. self.plot_all()
  4720. def grid_status(self):
  4721. return True if self.ui.grid_snap_btn.isChecked() else False
  4722. def populate_cmenu_grids(self):
  4723. units = self.defaults['units'].lower()
  4724. # for act in self.ui.cmenu_gridmenu.actions():
  4725. # act.triggered.disconnect()
  4726. self.ui.cmenu_gridmenu.clear()
  4727. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4728. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4729. _("Grid On/Off"))
  4730. grid_toggle.setCheckable(True)
  4731. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4732. self.ui.cmenu_gridmenu.addSeparator()
  4733. for grid in sorted_list:
  4734. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4735. "%s" % str(grid))
  4736. action.triggered.connect(self.set_grid)
  4737. self.ui.cmenu_gridmenu.addSeparator()
  4738. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4739. _("Add"))
  4740. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4741. _("Delete"))
  4742. grid_add.triggered.connect(self.on_grid_add)
  4743. grid_delete.triggered.connect(self.on_grid_delete)
  4744. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4745. def set_grid(self):
  4746. menu_action = self.sender()
  4747. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4748. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4749. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4750. def on_grid_add(self):
  4751. # ## Current application units in lower Case
  4752. units = self.defaults['units'].lower()
  4753. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4754. text=_('Enter a Grid Value:'),
  4755. min=0.0000, max=99.9999, decimals=4)
  4756. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4757. val, ok = grid_add_popup.get_value()
  4758. if ok:
  4759. if float(val) == 0:
  4760. self.inform.emit('[WARNING_NOTCL] %s' %
  4761. _("Please enter a grid value with non-zero value, in Float format."))
  4762. return
  4763. else:
  4764. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4765. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4766. self.inform.emit('[success] %s...' % _("New Grid added"))
  4767. else:
  4768. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4769. else:
  4770. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4771. def on_grid_delete(self):
  4772. # ## Current application units in lower Case
  4773. units = self.defaults['units'].lower()
  4774. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4775. text='Enter a Grid Value:',
  4776. min=0.0000, max=99.9999, decimals=4)
  4777. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4778. val, ok = grid_del_popup.get_value()
  4779. if ok:
  4780. if float(val) == 0:
  4781. self.inform.emit('[WARNING_NOTCL] %s' %
  4782. _("Please enter a grid value with non-zero value, in Float format."))
  4783. return
  4784. else:
  4785. try:
  4786. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4787. except ValueError:
  4788. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4789. return
  4790. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4791. else:
  4792. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4793. def on_shortcut_list(self):
  4794. self.defaults.report_usage("on_shortcut_list()")
  4795. # add the tab if it was closed
  4796. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4797. # delete the absolute and relative position and messages in the infobar
  4798. self.ui.position_label.setText("")
  4799. # self.ui.rel_position_label.setText("")
  4800. # Switch plot_area to preferences page
  4801. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4802. # self.ui.show()
  4803. def on_select_tab(self, name):
  4804. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4805. if self.ui.splitter.sizes()[0] == 0:
  4806. self.ui.splitter.setSizes([1, 1])
  4807. else:
  4808. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4809. self.ui.splitter.setSizes([0, 1])
  4810. if name == 'project':
  4811. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4812. elif name == 'selected':
  4813. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4814. elif name == 'tool':
  4815. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4816. def on_copy_name(self):
  4817. self.defaults.report_usage("on_copy_name()")
  4818. obj = self.collection.get_active()
  4819. try:
  4820. name = obj.options["name"]
  4821. except AttributeError:
  4822. log.debug("on_copy_name() --> No object selected to copy it's name")
  4823. self.inform.emit('[WARNING_NOTCL] %s' %
  4824. _(" No object selected to copy it's name"))
  4825. return
  4826. self.clipboard.setText(name)
  4827. self.inform.emit(_("Name copied on clipboard ..."))
  4828. def on_mouse_click_over_plot(self, event):
  4829. """
  4830. Default actions are:
  4831. :param event: Contains information about the event, like which button
  4832. was clicked, the pixel coordinates and the axes coordinates.
  4833. :return: None
  4834. """
  4835. self.pos = []
  4836. if self.is_legacy is False:
  4837. event_pos = event.pos
  4838. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4839. # # Set the mouse button for panning
  4840. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4841. else:
  4842. event_pos = (event.xdata, event.ydata)
  4843. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4844. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4845. # So it can receive key presses
  4846. self.plotcanvas.native.setFocus()
  4847. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4848. if self.grid_status():
  4849. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4850. else:
  4851. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4852. try:
  4853. if event.button == 1:
  4854. # Reset here the relative coordinates so there is a new reference on the click position
  4855. if self.rel_point1 is None:
  4856. self.rel_point1 = self.pos
  4857. else:
  4858. self.rel_point2 = copy(self.rel_point1)
  4859. self.rel_point1 = self.pos
  4860. self.on_mouse_move_over_plot(event, origin_click=True)
  4861. except Exception as e:
  4862. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4863. def on_mouse_double_click_over_plot(self, event):
  4864. if event.button == 1:
  4865. self.doubleclick = True
  4866. def on_mouse_move_over_plot(self, event, origin_click=None):
  4867. """
  4868. Callback for the mouse motion event over the plot.
  4869. :param event: Contains information about the event.
  4870. :param origin_click
  4871. :return: None
  4872. """
  4873. if self.is_legacy is False:
  4874. event_pos = event.pos
  4875. if self.defaults["global_pan_button"] == '2':
  4876. pan_button = 2
  4877. else:
  4878. pan_button = 3
  4879. self.event_is_dragging = event.is_dragging
  4880. else:
  4881. event_pos = (event.xdata, event.ydata)
  4882. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4883. if self.defaults["global_pan_button"] == '2':
  4884. pan_button = 3
  4885. else:
  4886. pan_button = 2
  4887. self.event_is_dragging = self.plotcanvas.is_dragging
  4888. # So it can receive key presses but not when the Tcl Shell is active
  4889. if not self.ui.shell_dock.isVisible():
  4890. if not self.plotcanvas.native.hasFocus():
  4891. self.plotcanvas.native.setFocus()
  4892. self.pos_jump = event_pos
  4893. self.ui.popMenu.mouse_is_panning = False
  4894. if origin_click is None:
  4895. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4896. if event.button == pan_button and self.event_is_dragging == 1:
  4897. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4898. if self.ui.popMenu.popup_active:
  4899. self.ui.popMenu.popup_active = False
  4900. return
  4901. self.ui.popMenu.mouse_is_panning = True
  4902. return
  4903. if self.rel_point1 is not None:
  4904. try: # May fail in case mouse not within axes
  4905. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4906. if pos_canvas[0] is None or pos_canvas[1] is None:
  4907. return
  4908. if self.grid_status():
  4909. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4910. # Update cursor
  4911. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4912. symbol='++', edge_color=self.cursor_color_3D,
  4913. edge_width=self.defaults["global_cursor_width"],
  4914. size=self.defaults["global_cursor_size"])
  4915. else:
  4916. pos = (pos_canvas[0], pos_canvas[1])
  4917. self.dx = pos[0] - float(self.rel_point1[0])
  4918. self.dy = pos[1] - float(self.rel_point1[1])
  4919. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4920. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4921. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4922. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4923. units = self.defaults["units"].lower()
  4924. self.plotcanvas.text_hud.text = \
  4925. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4926. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4927. self.mouse = [pos[0], pos[1]]
  4928. # if the mouse is moved and the LMB is clicked then the action is a selection
  4929. if self.event_is_dragging == 1 and event.button == 1:
  4930. self.delete_selection_shape()
  4931. if self.dx < 0:
  4932. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4933. face_color=self.defaults['global_alt_sel_fill'])
  4934. self.selection_type = False
  4935. elif self.dx >= 0:
  4936. self.draw_moving_selection_shape(self.pos, pos)
  4937. self.selection_type = True
  4938. else:
  4939. self.selection_type = None
  4940. else:
  4941. self.selection_type = None
  4942. # hover effect - enabled in Preferences -> General -> appGUI Settings
  4943. if self.defaults['global_hover']:
  4944. for obj in self.collection.get_list():
  4945. try:
  4946. # select the object(s) only if it is enabled (plotted)
  4947. if obj.options['plot']:
  4948. if obj not in self.collection.get_selected():
  4949. poly_obj = Polygon(
  4950. [(obj.options['xmin'], obj.options['ymin']),
  4951. (obj.options['xmax'], obj.options['ymin']),
  4952. (obj.options['xmax'], obj.options['ymax']),
  4953. (obj.options['xmin'], obj.options['ymax'])]
  4954. )
  4955. if Point(pos).within(poly_obj):
  4956. if obj.isHovering is False:
  4957. obj.isHovering = True
  4958. obj.notHovering = True
  4959. # create the selection box around the selected object
  4960. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4961. else:
  4962. if obj.notHovering is True:
  4963. obj.notHovering = False
  4964. obj.isHovering = False
  4965. self.delete_hover_shape()
  4966. except Exception:
  4967. # the Exception here will happen if we try to select on screen and we have an
  4968. # newly (and empty) just created Geometry or Excellon object that do not have the
  4969. # xmin, xmax, ymin, ymax options.
  4970. # In this case poly_obj creation (see above) will fail
  4971. pass
  4972. except Exception as e:
  4973. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4974. self.ui.position_label.setText("")
  4975. # self.ui.rel_position_label.setText("")
  4976. self.mouse = None
  4977. def on_mouse_click_release_over_plot(self, event):
  4978. """
  4979. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4980. and has been registered in ''self.__init__()''.
  4981. :param event: contains information about the event.
  4982. :return:
  4983. """
  4984. if self.is_legacy is False:
  4985. event_pos = event.pos
  4986. right_button = 2
  4987. else:
  4988. event_pos = (event.xdata, event.ydata)
  4989. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4990. right_button = 3
  4991. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4992. if self.grid_status():
  4993. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4994. else:
  4995. pos = (pos_canvas[0], pos_canvas[1])
  4996. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4997. # canvas menu
  4998. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4999. self.ui.popMenu.mouse_is_panning = False
  5000. self.cursor = QtGui.QCursor()
  5001. self.populate_cmenu_grids()
  5002. self.ui.popMenu.popup(self.cursor.pos())
  5003. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5004. # selection and then select a type of selection ("enclosing" or "touching")
  5005. if event.button == 1: # left click
  5006. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5007. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5008. if modifiers == QtCore.Qt.ShiftModifier:
  5009. # do not auto open the Project Tab
  5010. self.click_noproject = True
  5011. self.clipboard.setText(
  5012. self.defaults["global_point_clipboard_format"] %
  5013. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5014. )
  5015. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5016. return
  5017. if self.doubleclick is True:
  5018. self.doubleclick = False
  5019. if self.collection.get_selected():
  5020. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5021. if self.ui.splitter.sizes()[0] == 0:
  5022. self.ui.splitter.setSizes([1, 1])
  5023. try:
  5024. # delete the selection shape(S) as it may be in the way
  5025. self.delete_selection_shape()
  5026. self.delete_hover_shape()
  5027. except Exception as e:
  5028. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5029. return
  5030. else:
  5031. # WORKAROUND for LEGACY MODE
  5032. if self.is_legacy is True:
  5033. # if there is no move on canvas then we have no dragging selection
  5034. if self.dx == 0 or self.dy == 0:
  5035. self.selection_type = None
  5036. if self.selection_type is not None:
  5037. try:
  5038. self.selection_area_handler(self.pos, pos, self.selection_type)
  5039. self.selection_type = None
  5040. except Exception as e:
  5041. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5042. return
  5043. else:
  5044. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5045. if key_modifier == QtCore.Qt.ShiftModifier:
  5046. mod_key = 'Shift'
  5047. elif key_modifier == QtCore.Qt.ControlModifier:
  5048. mod_key = 'Control'
  5049. else:
  5050. mod_key = None
  5051. try:
  5052. if self.command_active is None:
  5053. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5054. # deselect, and if it's not selected then it will be selected
  5055. # If there is no active command (self.command_active is None) then we check if we clicked
  5056. # on a object by checking the bounding limits against mouse click position
  5057. if mod_key == self.defaults["global_mselect_key"]:
  5058. self.select_objects(key='multisel')
  5059. else:
  5060. # If there is no active command (self.command_active is None) then we check if
  5061. # we clicked on a object by checking the bounding limits against mouse click position
  5062. self.select_objects()
  5063. self.delete_hover_shape()
  5064. except Exception as e:
  5065. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5066. return
  5067. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5068. """
  5069. :param start_pos: mouse position when the selection LMB click was done
  5070. :param end_pos: mouse position when the left mouse button is released
  5071. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5072. :return:
  5073. """
  5074. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5075. # delete previous selection shape
  5076. self.delete_selection_shape()
  5077. # make all objects inactive
  5078. self.collection.set_all_inactive()
  5079. for obj in self.collection.get_list():
  5080. try:
  5081. # select the object(s) only if it is enabled (plotted)
  5082. if obj.options['plot']:
  5083. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5084. (obj.options['xmax'], obj.options['ymin']),
  5085. (obj.options['xmax'], obj.options['ymax']),
  5086. (obj.options['xmin'], obj.options['ymax'])])
  5087. if sel_type is True:
  5088. if poly_obj.within(poly_selection):
  5089. # create the selection box around the selected object
  5090. if self.defaults['global_selection_shape'] is True:
  5091. self.draw_selection_shape(obj)
  5092. self.collection.set_active(obj.options['name'])
  5093. else:
  5094. if poly_selection.intersects(poly_obj):
  5095. # create the selection box around the selected object
  5096. if self.defaults['global_selection_shape'] is True:
  5097. self.draw_selection_shape(obj)
  5098. self.collection.set_active(obj.options['name'])
  5099. obj.selection_shape_drawn = True
  5100. except Exception as e:
  5101. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5102. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5103. # In this case poly_obj creation (see above) will fail
  5104. log.debug("App.selection_area_handler() --> %s" % str(e))
  5105. def select_objects(self, key=None):
  5106. """
  5107. Will select objects clicked on canvas
  5108. :param key: for future use in cumulative selection
  5109. :return:
  5110. """
  5111. # list where we store the overlapped objects under our mouse left click position
  5112. if key is None:
  5113. self.objects_under_the_click_list = []
  5114. # Populate the list with the overlapped objects on the click position
  5115. curr_x, curr_y = self.pos
  5116. for obj in self.all_objects_list:
  5117. # ScriptObject and DocumentObject objects can't be selected
  5118. if obj.kind == 'script' or obj.kind == 'document':
  5119. continue
  5120. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5121. continue
  5122. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5123. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5124. if obj.options['name'] not in self.objects_under_the_click_list:
  5125. if obj.options['plot']:
  5126. # add objects to the objects_under_the_click list only if the object is plotted
  5127. # (active and not disabled)
  5128. self.objects_under_the_click_list.append(obj.options['name'])
  5129. try:
  5130. if self.objects_under_the_click_list:
  5131. curr_sel_obj = self.collection.get_active()
  5132. # case when there is only an object under the click and we toggle it
  5133. if len(self.objects_under_the_click_list) == 1:
  5134. if curr_sel_obj is None:
  5135. self.collection.set_active(self.objects_under_the_click_list[0])
  5136. curr_sel_obj = self.collection.get_active()
  5137. # create the selection box around the selected object
  5138. if self.defaults['global_selection_shape'] is True:
  5139. self.draw_selection_shape(curr_sel_obj)
  5140. curr_sel_obj.selection_shape_drawn = True
  5141. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5142. self.collection.on_objects_selection(False)
  5143. self.delete_selection_shape()
  5144. curr_sel_obj.selection_shape_drawn = False
  5145. self.collection.set_active(self.objects_under_the_click_list[0])
  5146. curr_sel_obj = self.collection.get_active()
  5147. # create the selection box around the selected object
  5148. if self.defaults['global_selection_shape'] is True:
  5149. self.draw_selection_shape(curr_sel_obj)
  5150. curr_sel_obj.selection_shape_drawn = True
  5151. self.selected_message(curr_sel_obj=curr_sel_obj)
  5152. elif curr_sel_obj.selection_shape_drawn is False:
  5153. if self.defaults['global_selection_shape'] is True:
  5154. self.draw_selection_shape(curr_sel_obj)
  5155. curr_sel_obj.selection_shape_drawn = True
  5156. else:
  5157. self.collection.on_objects_selection(False)
  5158. self.delete_selection_shape()
  5159. if self.call_source != 'app':
  5160. self.call_source = 'app'
  5161. self.selected_message(curr_sel_obj=curr_sel_obj)
  5162. else:
  5163. # If there is no selected object
  5164. # make active the first element of the overlapped objects list
  5165. if self.collection.get_active() is None:
  5166. self.collection.set_active(self.objects_under_the_click_list[0])
  5167. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5168. name_sel_obj = self.collection.get_active().options['name']
  5169. # In case that there is a selected object but it is not in the overlapped object list
  5170. # make that object inactive and activate the first element in the overlapped object list
  5171. if name_sel_obj not in self.objects_under_the_click_list:
  5172. self.collection.set_inactive(name_sel_obj)
  5173. name_sel_obj = self.objects_under_the_click_list[0]
  5174. self.collection.set_active(name_sel_obj)
  5175. else:
  5176. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5177. self.collection.set_all_inactive()
  5178. self.collection.set_active(
  5179. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5180. curr_sel_obj = self.collection.get_active()
  5181. # delete the possible selection box around a possible selected object
  5182. self.delete_selection_shape()
  5183. curr_sel_obj.selection_shape_drawn = False
  5184. # create the selection box around the selected object
  5185. if self.defaults['global_selection_shape'] is True:
  5186. self.draw_selection_shape(curr_sel_obj)
  5187. curr_sel_obj.selection_shape_drawn = True
  5188. self.selected_message(curr_sel_obj=curr_sel_obj)
  5189. else:
  5190. # deselect everything
  5191. self.collection.on_objects_selection(False)
  5192. # delete the possible selection box around a possible selected object
  5193. self.delete_selection_shape()
  5194. for o in self.collection.get_list():
  5195. o.selection_shape_drawn = False
  5196. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5197. # only when working on App
  5198. if self.call_source == 'app':
  5199. if self.click_noproject is False:
  5200. # if the Tool Tab is in focus don't change focus to Project Tab
  5201. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5202. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5203. else:
  5204. # restore auto open the Project Tab
  5205. self.click_noproject = False
  5206. # delete any text in the status bar, implicitly the last object name that was selected
  5207. # self.inform.emit("")
  5208. else:
  5209. self.call_source = 'app'
  5210. except Exception as e:
  5211. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5212. def selected_message(self, curr_sel_obj):
  5213. if curr_sel_obj:
  5214. if curr_sel_obj.kind == 'gerber':
  5215. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5216. color='green',
  5217. name=str(curr_sel_obj.options['name']),
  5218. tx=_("selected"))
  5219. )
  5220. elif curr_sel_obj.kind == 'excellon':
  5221. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5222. color='brown',
  5223. name=str(curr_sel_obj.options['name']),
  5224. tx=_("selected"))
  5225. )
  5226. elif curr_sel_obj.kind == 'cncjob':
  5227. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5228. color='blue',
  5229. name=str(curr_sel_obj.options['name']),
  5230. tx=_("selected"))
  5231. )
  5232. elif curr_sel_obj.kind == 'geometry':
  5233. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5234. color='red',
  5235. name=str(curr_sel_obj.options['name']),
  5236. tx=_("selected"))
  5237. )
  5238. def delete_hover_shape(self):
  5239. self.hover_shapes.clear()
  5240. self.hover_shapes.redraw()
  5241. def draw_hover_shape(self, sel_obj, color=None):
  5242. """
  5243. :param sel_obj: The object for which the hover shape must be drawn
  5244. :param color: The color of the hover shape
  5245. :return: None
  5246. """
  5247. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5248. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5249. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5250. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5251. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5252. if self.defaults['units'].upper() == 'MM':
  5253. hover_rect = hover_rect.buffer(-0.1)
  5254. hover_rect = hover_rect.buffer(0.2)
  5255. else:
  5256. hover_rect = hover_rect.buffer(-0.00393)
  5257. hover_rect = hover_rect.buffer(0.00787)
  5258. # if color:
  5259. # face = Color(color)
  5260. # face.alpha = 0.2
  5261. # outline = Color(color, alpha=0.8)
  5262. # else:
  5263. # face = Color(self.defaults['global_sel_fill'])
  5264. # face.alpha = 0.2
  5265. # outline = self.defaults['global_sel_line']
  5266. if color:
  5267. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5268. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5269. else:
  5270. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5271. outline = self.defaults['global_sel_line']
  5272. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5273. if self.is_legacy is True:
  5274. self.hover_shapes.redraw()
  5275. def delete_selection_shape(self):
  5276. self.move_tool.sel_shapes.clear()
  5277. self.move_tool.sel_shapes.redraw()
  5278. def draw_selection_shape(self, sel_obj, color=None):
  5279. """
  5280. Will draw a selection shape around the selected object.
  5281. :param sel_obj: The object for which the selection shape must be drawn
  5282. :param color: The color for the selection shape.
  5283. :return: None
  5284. """
  5285. if sel_obj is None:
  5286. return
  5287. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5288. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5289. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5290. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5291. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5292. if self.defaults['units'].upper() == 'MM':
  5293. sel_rect = sel_rect.buffer(-0.1)
  5294. sel_rect = sel_rect.buffer(0.2)
  5295. else:
  5296. sel_rect = sel_rect.buffer(-0.00393)
  5297. sel_rect = sel_rect.buffer(0.00787)
  5298. if color:
  5299. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5300. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5301. else:
  5302. if self.is_legacy is False:
  5303. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5304. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5305. else:
  5306. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5307. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5308. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5309. color=outline,
  5310. face_color=face,
  5311. update=True,
  5312. layer=0,
  5313. tolerance=None))
  5314. if self.is_legacy is True:
  5315. self.move_tool.sel_shapes.redraw()
  5316. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5317. """
  5318. Will draw a selection shape when dragging mouse on canvas.
  5319. :param old_coords: Old coordinates
  5320. :param coords: New coordinates
  5321. :param kwargs: Keyword arguments
  5322. :return:
  5323. """
  5324. if 'color' in kwargs:
  5325. color = kwargs['color']
  5326. else:
  5327. color = self.defaults['global_sel_line']
  5328. if 'face_color' in kwargs:
  5329. face_color = kwargs['face_color']
  5330. else:
  5331. face_color = self.defaults['global_sel_fill']
  5332. if 'face_alpha' in kwargs:
  5333. face_alpha = kwargs['face_alpha']
  5334. else:
  5335. face_alpha = 0.3
  5336. x0, y0 = old_coords
  5337. x1, y1 = coords
  5338. pt1 = (x0, y0)
  5339. pt2 = (x1, y0)
  5340. pt3 = (x1, y1)
  5341. pt4 = (x0, y1)
  5342. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5343. # color_t = Color(face_color)
  5344. # color_t.alpha = face_alpha
  5345. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5346. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5347. layer=0, tolerance=None)
  5348. if self.is_legacy is True:
  5349. self.move_tool.sel_shapes.redraw()
  5350. def on_file_new_click(self):
  5351. """
  5352. Callback for menu item File -> New.
  5353. Executed on clicking the Menu -> File -> New Project
  5354. :return:
  5355. """
  5356. if self.collection.get_list() and self.should_we_save:
  5357. msgbox = QtWidgets.QMessageBox()
  5358. # msgbox.setText("<B>Save changes ...</B>")
  5359. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5360. "Creating a New project will delete them.\n"
  5361. "Do you want to Save the project?"))
  5362. msgbox.setWindowTitle(_("Save changes"))
  5363. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5364. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5365. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5366. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5367. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5368. msgbox.setDefaultButton(bt_yes)
  5369. msgbox.exec_()
  5370. response = msgbox.clickedButton()
  5371. if response == bt_yes:
  5372. self.on_file_saveprojectas()
  5373. elif response == bt_cancel:
  5374. return
  5375. elif response == bt_no:
  5376. self.on_file_new()
  5377. else:
  5378. self.on_file_new()
  5379. self.inform.emit('[success] %s...' % _("New Project created"))
  5380. def on_file_new(self, cli=None):
  5381. """
  5382. Returns the application to its startup state. This method is thread-safe.
  5383. :param cli: Boolean. If True this method was run from command line
  5384. :return: None
  5385. """
  5386. self.defaults.report_usage("on_file_new")
  5387. # Remove everything from memory
  5388. App.log.debug("on_file_new()")
  5389. # close any editor that might be open
  5390. if self.call_source != 'app':
  5391. self.editor2object(cleanup=True)
  5392. # ## EDITOR section
  5393. self.geo_editor = FlatCAMGeoEditor(self)
  5394. self.exc_editor = FlatCAMExcEditor(self)
  5395. self.grb_editor = FlatCAMGrbEditor(self)
  5396. # Clear pool
  5397. self.clear_pool()
  5398. for obj in self.collection.get_list():
  5399. # delete shapes left drawn from mark shape_collections, if any
  5400. if isinstance(obj, GerberObject):
  5401. try:
  5402. for el in obj.mark_shapes:
  5403. obj.mark_shapes[el].clear(update=True)
  5404. obj.mark_shapes[el].enabled = False
  5405. del el
  5406. except AttributeError:
  5407. pass
  5408. # also delete annotation shapes, if any
  5409. elif isinstance(obj, CNCJobObject):
  5410. try:
  5411. obj.text_col.enabled = False
  5412. del obj.text_col
  5413. obj.annotation.clear(update=True)
  5414. del obj.annotation
  5415. except AttributeError:
  5416. pass
  5417. # delete the exclusion areas
  5418. self.exc_areas.clear_shapes()
  5419. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5420. self.shell.init_tcl()
  5421. # delete any selection shape on canvas
  5422. self.delete_selection_shape()
  5423. # delete all FlatCAM objects
  5424. self.collection.delete_all()
  5425. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5426. self.setup_component_editor()
  5427. # Clear project filename
  5428. self.project_filename = None
  5429. # Load the application defaults
  5430. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5431. # Re-fresh project options
  5432. self.on_options_app2project()
  5433. # Init FlatCAMTools
  5434. self.init_tools()
  5435. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5436. if cli is None:
  5437. # we need to go in reverse because once we remove a tab then the index changes
  5438. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5439. # and so on. Therefore the deletion should be done in reverse
  5440. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5441. for index in range(wdg_count, -1, -1):
  5442. try:
  5443. self.ui.plot_tab_area.closeTab(index)
  5444. except Exception as e:
  5445. log.debug("App.on_file_new() --> %s" % str(e))
  5446. # # And then add again the Plot Area
  5447. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5448. self.ui.plot_tab_area.protectTab(0)
  5449. # take the focus of the Notebook on Project Tab.
  5450. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5451. self.set_ui_title(name=_("New Project - Not saved"))
  5452. def obj_properties(self):
  5453. """
  5454. Will launch the object Properties Tool
  5455. :return:
  5456. """
  5457. self.defaults.report_usage("obj_properties()")
  5458. self.properties_tool.run(toggle=False)
  5459. def on_project_context_save(self):
  5460. """
  5461. Wrapper, will save the object function of it's type
  5462. :return:
  5463. """
  5464. obj = self.collection.get_active()
  5465. if type(obj) == GeometryObject:
  5466. self.on_file_exportdxf()
  5467. elif type(obj) == ExcellonObject:
  5468. self.on_file_saveexcellon()
  5469. elif type(obj) == CNCJobObject:
  5470. obj.on_exportgcode_button_click()
  5471. elif type(obj) == GerberObject:
  5472. self.on_file_savegerber()
  5473. elif type(obj) == ScriptObject:
  5474. self.on_file_savescript()
  5475. elif type(obj) == DocumentObject:
  5476. self.on_file_savedocument()
  5477. def obj_move(self):
  5478. """
  5479. Callback for the Move menu entry in various Context Menu's.
  5480. :return:
  5481. """
  5482. self.defaults.report_usage("obj_move()")
  5483. self.move_tool.run(toggle=False)
  5484. def on_fileopengerber(self, signal, name=None):
  5485. """
  5486. File menu callback for opening a Gerber.
  5487. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5488. :param name:
  5489. :return: None
  5490. """
  5491. self.defaults.report_usage("on_fileopengerber")
  5492. App.log.debug("on_fileopengerber()")
  5493. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5494. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5495. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5496. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5497. "*.outline);;" \
  5498. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5499. "*.mil);;" \
  5500. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5501. "Allegro Files (*.art);;" \
  5502. "Mentor Files (*.pho *.gdo);;" \
  5503. "All Files (*.*)"
  5504. if name is None:
  5505. try:
  5506. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5507. directory=self.get_last_folder(),
  5508. filter=_filter_,
  5509. initialFilter=self.last_op_gerber_filter)
  5510. except TypeError:
  5511. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5512. filenames = [str(filename) for filename in filenames]
  5513. self.last_op_gerber_filter = _f
  5514. else:
  5515. filenames = [name]
  5516. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5517. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5518. _("Opening Gerber file.")),
  5519. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5520. color=QtGui.QColor("gray"))
  5521. if len(filenames) == 0:
  5522. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5523. else:
  5524. for filename in filenames:
  5525. if filename != '':
  5526. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5527. def on_fileopenexcellon(self, signal, name=None):
  5528. """
  5529. File menu callback for opening an Excellon file.
  5530. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5531. :param name:
  5532. :return: None
  5533. """
  5534. self.defaults.report_usage("on_fileopenexcellon")
  5535. App.log.debug("on_fileopenexcellon()")
  5536. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5537. "All Files (*.*)"
  5538. if name is None:
  5539. try:
  5540. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5541. directory=self.get_last_folder(),
  5542. filter=_filter_,
  5543. initialFilter=self.last_op_excellon_filter)
  5544. except TypeError:
  5545. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5546. filenames = [str(filename) for filename in filenames]
  5547. self.last_op_excellon_filter = _f
  5548. else:
  5549. filenames = [str(name)]
  5550. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5551. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5552. _("Opening Excellon file.")),
  5553. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5554. color=QtGui.QColor("gray"))
  5555. if len(filenames) == 0:
  5556. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5557. else:
  5558. for filename in filenames:
  5559. if filename != '':
  5560. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5561. def on_fileopengcode(self, signal, name=None):
  5562. """
  5563. File menu call back for opening gcode.
  5564. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5565. :param name:
  5566. :return:
  5567. """
  5568. self.defaults.report_usage("on_fileopengcode")
  5569. App.log.debug("on_fileopengcode()")
  5570. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5571. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5572. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5573. "All Files (*.*)"
  5574. if name is None:
  5575. try:
  5576. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5577. directory=self.get_last_folder(),
  5578. filter=_filter_,
  5579. initialFilter=self.last_op_gcode_filter)
  5580. except TypeError:
  5581. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5582. filenames = [str(filename) for filename in filenames]
  5583. self.last_op_gcode_filter = _f
  5584. else:
  5585. filenames = [name]
  5586. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5587. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5588. _("Opening G-Code file.")),
  5589. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5590. color=QtGui.QColor("gray"))
  5591. if len(filenames) == 0:
  5592. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5593. else:
  5594. for filename in filenames:
  5595. if filename != '':
  5596. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5597. def on_file_openproject(self, signal):
  5598. """
  5599. File menu callback for opening a project.
  5600. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5601. :return: None
  5602. """
  5603. self.defaults.report_usage("on_file_openproject")
  5604. App.log.debug("on_file_openproject()")
  5605. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5606. try:
  5607. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5608. directory=self.get_last_folder(), filter=_filter_)
  5609. except TypeError:
  5610. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5611. # The Qt methods above will return a QString which can cause problems later.
  5612. # So far json.dump() will fail to serialize it.
  5613. # TODO: Improve the serialization methods and remove this fix.
  5614. filename = str(filename)
  5615. if filename == "":
  5616. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5617. else:
  5618. # self.worker_task.emit({'fcn': self.open_project,
  5619. # 'params': [filename]})
  5620. # The above was failing because open_project() is not
  5621. # thread safe. The new_project()
  5622. self.open_project(filename)
  5623. def on_fileopenhpgl2(self, signal, name=None):
  5624. """
  5625. File menu callback for opening a HPGL2.
  5626. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5627. :param name:
  5628. :return: None
  5629. """
  5630. self.defaults.report_usage("on_fileopenhpgl2")
  5631. App.log.debug("on_fileopenhpgl2()")
  5632. _filter_ = "HPGL2 Files (*.plt);;" \
  5633. "All Files (*.*)"
  5634. if name is None:
  5635. try:
  5636. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5637. directory=self.get_last_folder(),
  5638. filter=_filter_)
  5639. except TypeError:
  5640. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5641. filenames = [str(filename) for filename in filenames]
  5642. else:
  5643. filenames = [name]
  5644. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5645. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5646. _("Opening HPGL2 file.")),
  5647. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5648. color=QtGui.QColor("gray"))
  5649. if len(filenames) == 0:
  5650. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5651. else:
  5652. for filename in filenames:
  5653. if filename != '':
  5654. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5655. def on_file_openconfig(self, signal):
  5656. """
  5657. File menu callback for opening a config file.
  5658. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5659. :return: None
  5660. """
  5661. self.defaults.report_usage("on_file_openconfig")
  5662. App.log.debug("on_file_openconfig()")
  5663. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5664. try:
  5665. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5666. directory=self.data_path, filter=_filter_)
  5667. except TypeError:
  5668. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5669. filter=_filter_)
  5670. if filename == "":
  5671. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5672. else:
  5673. self.open_config_file(filename)
  5674. def on_file_exportsvg(self):
  5675. """
  5676. Callback for menu item File->Export SVG.
  5677. :return: None
  5678. """
  5679. self.defaults.report_usage("on_file_exportsvg")
  5680. App.log.debug("on_file_exportsvg()")
  5681. obj = self.collection.get_active()
  5682. if obj is None:
  5683. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5684. msg = _("Please Select a Geometry object to export")
  5685. msgbox = QtWidgets.QMessageBox()
  5686. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5687. msgbox.setInformativeText(msg)
  5688. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5689. msgbox.setDefaultButton(bt_ok)
  5690. msgbox.exec_()
  5691. return
  5692. # Check for more compatible types and add as required
  5693. if (not isinstance(obj, GeometryObject)
  5694. and not isinstance(obj, GerberObject)
  5695. and not isinstance(obj, CNCJobObject)
  5696. and not isinstance(obj, ExcellonObject)):
  5697. msg = '[ERROR_NOTCL] %s' % \
  5698. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5699. msgbox = QtWidgets.QMessageBox()
  5700. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5701. msgbox.setInformativeText(msg)
  5702. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5703. msgbox.setDefaultButton(bt_ok)
  5704. msgbox.exec_()
  5705. return
  5706. name = obj.options["name"]
  5707. _filter = "SVG File (*.svg);;All Files (*.*)"
  5708. try:
  5709. filename, _f = FCFileSaveDialog.get_saved_filename(
  5710. caption=_("Export SVG"),
  5711. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5712. ext_filter=_filter)
  5713. except TypeError:
  5714. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5715. filename = str(filename)
  5716. if filename == "":
  5717. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5718. return
  5719. else:
  5720. self.export_svg(name, filename)
  5721. if self.defaults["global_open_style"] is False:
  5722. self.file_opened.emit("SVG", filename)
  5723. self.file_saved.emit("SVG", filename)
  5724. def on_file_exportpng(self):
  5725. self.defaults.report_usage("on_file_exportpng")
  5726. App.log.debug("on_file_exportpng()")
  5727. self.date = str(datetime.today()).rpartition('.')[0]
  5728. self.date = ''.join(c for c in self.date if c not in ':-')
  5729. self.date = self.date.replace(' ', '_')
  5730. data = None
  5731. if self.is_legacy is False:
  5732. image = _screenshot(alpha=False)
  5733. data = np.asarray(image)
  5734. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5735. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5736. return
  5737. filter_ = "PNG File (*.png);;All Files (*.*)"
  5738. try:
  5739. filename, _f = FCFileSaveDialog.get_saved_filename(
  5740. caption=_("Export PNG Image"),
  5741. directory=self.get_last_save_folder() + '/png_' + self.date,
  5742. ext_filter=filter_)
  5743. except TypeError:
  5744. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5745. filename = str(filename)
  5746. if filename == "":
  5747. self.inform.emit(_("Cancelled."))
  5748. return
  5749. else:
  5750. if self.is_legacy is False:
  5751. write_png(filename, data)
  5752. else:
  5753. self.plotcanvas.figure.savefig(filename)
  5754. if self.defaults["global_open_style"] is False:
  5755. self.file_opened.emit("png", filename)
  5756. self.file_saved.emit("png", filename)
  5757. def on_file_savegerber(self):
  5758. """
  5759. Callback for menu item in Project context menu.
  5760. :return: None
  5761. """
  5762. self.defaults.report_usage("on_file_savegerber")
  5763. App.log.debug("on_file_savegerber()")
  5764. obj = self.collection.get_active()
  5765. if obj is None:
  5766. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5767. return
  5768. # Check for more compatible types and add as required
  5769. if not isinstance(obj, GerberObject):
  5770. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5771. return
  5772. name = self.collection.get_active().options["name"]
  5773. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5774. try:
  5775. filename, _f = FCFileSaveDialog.get_saved_filename(
  5776. caption="Save Gerber source file",
  5777. directory=self.get_last_save_folder() + '/' + name,
  5778. ext_filter=_filter)
  5779. except TypeError:
  5780. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5781. filename = str(filename)
  5782. if filename == "":
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5784. return
  5785. else:
  5786. self.save_source_file(name, filename)
  5787. if self.defaults["global_open_style"] is False:
  5788. self.file_opened.emit("Gerber", filename)
  5789. self.file_saved.emit("Gerber", filename)
  5790. def on_file_savescript(self):
  5791. """
  5792. Callback for menu item in Project context menu.
  5793. :return: None
  5794. """
  5795. self.defaults.report_usage("on_file_savescript")
  5796. App.log.debug("on_file_savescript()")
  5797. obj = self.collection.get_active()
  5798. if obj is None:
  5799. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5800. return
  5801. # Check for more compatible types and add as required
  5802. if not isinstance(obj, ScriptObject):
  5803. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5804. return
  5805. name = self.collection.get_active().options["name"]
  5806. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5807. try:
  5808. filename, _f = FCFileSaveDialog.get_saved_filename(
  5809. caption="Save Script source file",
  5810. directory=self.get_last_save_folder() + '/' + name,
  5811. ext_filter=_filter)
  5812. except TypeError:
  5813. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5814. filename = str(filename)
  5815. if filename == "":
  5816. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5817. return
  5818. else:
  5819. self.save_source_file(name, filename)
  5820. if self.defaults["global_open_style"] is False:
  5821. self.file_opened.emit("Script", filename)
  5822. self.file_saved.emit("Script", filename)
  5823. def on_file_savedocument(self):
  5824. """
  5825. Callback for menu item in Project context menu.
  5826. :return: None
  5827. """
  5828. self.defaults.report_usage("on_file_savedocument")
  5829. App.log.debug("on_file_savedocument()")
  5830. obj = self.collection.get_active()
  5831. if obj is None:
  5832. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5833. return
  5834. # Check for more compatible types and add as required
  5835. if not isinstance(obj, ScriptObject):
  5836. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5837. return
  5838. name = self.collection.get_active().options["name"]
  5839. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5840. try:
  5841. filename, _f = FCFileSaveDialog.get_saved_filename(
  5842. caption="Save Document source file",
  5843. directory=self.get_last_save_folder() + '/' + name,
  5844. ext_filter=_filter)
  5845. except TypeError:
  5846. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5847. ext_filter=_filter)
  5848. filename = str(filename)
  5849. if filename == "":
  5850. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5851. return
  5852. else:
  5853. self.save_source_file(name, filename)
  5854. if self.defaults["global_open_style"] is False:
  5855. self.file_opened.emit("Document", filename)
  5856. self.file_saved.emit("Document", filename)
  5857. def on_file_saveexcellon(self):
  5858. """
  5859. Callback for menu item in project context menu.
  5860. :return: None
  5861. """
  5862. self.defaults.report_usage("on_file_saveexcellon")
  5863. App.log.debug("on_file_saveexcellon()")
  5864. obj = self.collection.get_active()
  5865. if obj is None:
  5866. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5867. return
  5868. # Check for more compatible types and add as required
  5869. if not isinstance(obj, ExcellonObject):
  5870. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5871. return
  5872. name = self.collection.get_active().options["name"]
  5873. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5874. try:
  5875. filename, _f = FCFileSaveDialog.get_saved_filename(
  5876. caption=_("Save Excellon source file"),
  5877. directory=self.get_last_save_folder() + '/' + name,
  5878. ext_filter=_filter)
  5879. except TypeError:
  5880. filename, _f = FCFileSaveDialog.get_saved_filename(
  5881. caption=_("Save Excellon source file"), ext_filter=_filter)
  5882. filename = str(filename)
  5883. if filename == "":
  5884. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5885. return
  5886. else:
  5887. self.save_source_file(name, filename)
  5888. if self.defaults["global_open_style"] is False:
  5889. self.file_opened.emit("Excellon", filename)
  5890. self.file_saved.emit("Excellon", filename)
  5891. def on_file_exportexcellon(self):
  5892. """
  5893. Callback for menu item File->Export->Excellon.
  5894. :return: None
  5895. """
  5896. self.defaults.report_usage("on_file_exportexcellon")
  5897. App.log.debug("on_file_exportexcellon()")
  5898. obj = self.collection.get_active()
  5899. if obj is None:
  5900. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5901. return
  5902. # Check for more compatible types and add as required
  5903. if not isinstance(obj, ExcellonObject):
  5904. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5905. return
  5906. name = self.collection.get_active().options["name"]
  5907. _filter = self.defaults["excellon_save_filters"]
  5908. try:
  5909. filename, _f = FCFileSaveDialog.get_saved_filename(
  5910. caption=_("Export Excellon"),
  5911. directory=self.get_last_save_folder() + '/' + name,
  5912. ext_filter=_filter)
  5913. except TypeError:
  5914. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5915. filename = str(filename)
  5916. if filename == "":
  5917. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5918. return
  5919. else:
  5920. used_extension = filename.rpartition('.')[2]
  5921. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5922. self.export_excellon(name, filename)
  5923. if self.defaults["global_open_style"] is False:
  5924. self.file_opened.emit("Excellon", filename)
  5925. self.file_saved.emit("Excellon", filename)
  5926. def on_file_exportgerber(self):
  5927. """
  5928. Callback for menu item File->Export->Gerber.
  5929. :return: None
  5930. """
  5931. self.defaults.report_usage("on_file_exportgerber")
  5932. App.log.debug("on_file_exportgerber()")
  5933. obj = self.collection.get_active()
  5934. if obj is None:
  5935. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5936. return
  5937. # Check for more compatible types and add as required
  5938. if not isinstance(obj, GerberObject):
  5939. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5940. return
  5941. name = self.collection.get_active().options["name"]
  5942. _filter_ = self.defaults['gerber_save_filters']
  5943. try:
  5944. filename, _f = FCFileSaveDialog.get_saved_filename(
  5945. caption=_("Export Gerber"),
  5946. directory=self.get_last_save_folder() + '/' + name,
  5947. ext_filter=_filter_)
  5948. except TypeError:
  5949. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5950. filename = str(filename)
  5951. if filename == "":
  5952. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5953. return
  5954. else:
  5955. used_extension = filename.rpartition('.')[2]
  5956. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5957. self.export_gerber(name, filename)
  5958. if self.defaults["global_open_style"] is False:
  5959. self.file_opened.emit("Gerber", filename)
  5960. self.file_saved.emit("Gerber", filename)
  5961. def on_file_exportdxf(self):
  5962. """
  5963. Callback for menu item File->Export DXF.
  5964. :return: None
  5965. """
  5966. self.defaults.report_usage("on_file_exportdxf")
  5967. App.log.debug("on_file_exportdxf()")
  5968. obj = self.collection.get_active()
  5969. if obj is None:
  5970. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5971. msg = _("Please Select a Geometry object to export")
  5972. msgbox = QtWidgets.QMessageBox()
  5973. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5974. msgbox.setInformativeText(msg)
  5975. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5976. msgbox.setDefaultButton(bt_ok)
  5977. msgbox.exec_()
  5978. return
  5979. # Check for more compatible types and add as required
  5980. if not isinstance(obj, GeometryObject):
  5981. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5982. msgbox = QtWidgets.QMessageBox()
  5983. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5984. msgbox.setInformativeText(msg)
  5985. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5986. msgbox.setDefaultButton(bt_ok)
  5987. msgbox.exec_()
  5988. return
  5989. name = self.collection.get_active().options["name"]
  5990. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5991. try:
  5992. filename, _f = FCFileSaveDialog.get_saved_filename(
  5993. caption=_("Export DXF"),
  5994. directory=self.get_last_save_folder() + '/' + name,
  5995. ext_filter=_filter_)
  5996. except TypeError:
  5997. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  5998. filename = str(filename)
  5999. if filename == "":
  6000. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6001. return
  6002. else:
  6003. self.export_dxf(name, filename)
  6004. if self.defaults["global_open_style"] is False:
  6005. self.file_opened.emit("DXF", filename)
  6006. self.file_saved.emit("DXF", filename)
  6007. def on_file_importsvg(self, type_of_obj):
  6008. """
  6009. Callback for menu item File->Import SVG.
  6010. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6011. :type type_of_obj: str
  6012. :return: None
  6013. """
  6014. self.defaults.report_usage("on_file_importsvg")
  6015. App.log.debug("on_file_importsvg()")
  6016. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6017. try:
  6018. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6019. directory=self.get_last_folder(), filter=_filter_)
  6020. except TypeError:
  6021. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6022. filter=_filter_)
  6023. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6024. type_of_obj = "geometry"
  6025. filenames = [str(filename) for filename in filenames]
  6026. if len(filenames) == 0:
  6027. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6028. else:
  6029. for filename in filenames:
  6030. if filename != '':
  6031. self.worker_task.emit({'fcn': self.import_svg,
  6032. 'params': [filename, type_of_obj]})
  6033. def on_file_importdxf(self, type_of_obj):
  6034. """
  6035. Callback for menu item File->Import DXF.
  6036. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6037. :type type_of_obj: str
  6038. :return: None
  6039. """
  6040. self.defaults.report_usage("on_file_importdxf")
  6041. App.log.debug("on_file_importdxf()")
  6042. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6043. try:
  6044. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6045. directory=self.get_last_folder(),
  6046. filter=_filter_)
  6047. except TypeError:
  6048. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6049. filter=_filter_)
  6050. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6051. type_of_obj = "geometry"
  6052. filenames = [str(filename) for filename in filenames]
  6053. if len(filenames) == 0:
  6054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6055. else:
  6056. for filename in filenames:
  6057. if filename != '':
  6058. self.worker_task.emit({'fcn': self.import_dxf,
  6059. 'params': [filename, type_of_obj]})
  6060. # ###############################################################################################################
  6061. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6062. # ###############################################################################################################
  6063. def init_code_editor(self, name):
  6064. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6065. # add the tab if it was closed
  6066. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6067. self.text_editor_tab.setObjectName('text_editor_tab')
  6068. # delete the absolute and relative position and messages in the infobar
  6069. self.ui.position_label.setText("")
  6070. # self.ui.rel_position_label.setText("")
  6071. # first clear previous text in text editor (if any)
  6072. self.text_editor_tab.code_editor.clear()
  6073. self.text_editor_tab.code_editor.setReadOnly(False)
  6074. self.toggle_codeeditor = True
  6075. self.text_editor_tab.code_editor.completer_enable = False
  6076. self.text_editor_tab.buttonRun.hide()
  6077. # make sure to keep a reference to the code editor
  6078. self.reference_code_editor = self.text_editor_tab.code_editor
  6079. # Switch plot_area to CNCJob tab
  6080. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6081. def on_view_source(self):
  6082. """
  6083. Called when the user wants to see the source file of the selected object
  6084. :return:
  6085. """
  6086. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6087. self.proc_container.view.set_busy(_("Loading..."))
  6088. try:
  6089. obj = self.collection.get_active()
  6090. except Exception as e:
  6091. log.debug("App.on_view_source() --> %s" % str(e))
  6092. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6093. return 'fail'
  6094. if obj is None:
  6095. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6096. return 'fail'
  6097. flt = "All Files (*.*)"
  6098. if obj.kind == 'gerber':
  6099. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6100. elif obj.kind == 'excellon':
  6101. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6102. elif obj.kind == 'cncjob':
  6103. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6104. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6105. # add the tab if it was closed
  6106. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6107. self.source_editor_tab.setObjectName('source_editor_tab')
  6108. # delete the absolute and relative position and messages in the infobar
  6109. self.ui.position_label.setText("")
  6110. # self.ui.rel_position_label.setText("")
  6111. # first clear previous text in text editor (if any)
  6112. self.source_editor_tab.code_editor.clear()
  6113. self.source_editor_tab.code_editor.setReadOnly(False)
  6114. self.source_editor_tab.code_editor.completer_enable = False
  6115. self.source_editor_tab.buttonRun.hide()
  6116. # Switch plot_area to CNCJob tab
  6117. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6118. try:
  6119. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6120. except TypeError:
  6121. pass
  6122. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6123. try:
  6124. self.source_editor_tab.buttonSave.clicked.disconnect()
  6125. except TypeError:
  6126. pass
  6127. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6128. # then append the text from GCode to the text editor
  6129. if obj.kind == 'cncjob':
  6130. try:
  6131. file = obj.export_gcode(
  6132. preamble=self.defaults["cncjob_prepend"],
  6133. postamble=self.defaults["cncjob_append"],
  6134. to_file=True)
  6135. if file == 'fail':
  6136. return 'fail'
  6137. except AttributeError:
  6138. self.inform.emit('[WARNING_NOTCL] %s' %
  6139. _("There is no selected object for which to see it's source file code."))
  6140. return 'fail'
  6141. else:
  6142. try:
  6143. file = StringIO(obj.source_file)
  6144. except (AttributeError, TypeError):
  6145. self.inform.emit('[WARNING_NOTCL] %s' %
  6146. _("There is no selected object for which to see it's source file code."))
  6147. return 'fail'
  6148. self.source_editor_tab.t_frame.hide()
  6149. try:
  6150. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6151. # for line in file:
  6152. # QtWidgets.QApplication.processEvents()
  6153. # proc_line = str(line).strip('\n')
  6154. # self.source_editor_tab.code_editor.append(proc_line)
  6155. except Exception as e:
  6156. log.debug('App.on_view_source() -->%s' % str(e))
  6157. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6158. return
  6159. self.source_editor_tab.handleTextChanged()
  6160. self.source_editor_tab.t_frame.show()
  6161. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6162. self.proc_container.view.set_idle()
  6163. # self.ui.show()
  6164. def on_toggle_code_editor(self):
  6165. self.defaults.report_usage("on_toggle_code_editor()")
  6166. if self.toggle_codeeditor is False:
  6167. self.init_code_editor(name=_("Code Editor"))
  6168. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6169. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6170. self.text_editor_tab.buttonSave.clicked.disconnect()
  6171. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6172. else:
  6173. for idx in range(self.ui.plot_tab_area.count()):
  6174. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6175. self.ui.plot_tab_area.closeTab(idx)
  6176. break
  6177. self.toggle_codeeditor = False
  6178. def on_code_editor_close(self):
  6179. self.toggle_codeeditor = False
  6180. def goto_text_line(self):
  6181. """
  6182. Will scroll a text to the specified text line.
  6183. :return: None
  6184. """
  6185. dia_box = Dialog_box(title=_("Go to Line ..."),
  6186. label=_("Line:"),
  6187. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6188. initial_text='')
  6189. try:
  6190. line = int(dia_box.location) - 1
  6191. except (ValueError, TypeError):
  6192. line = 0
  6193. if dia_box.ok:
  6194. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6195. # at the top of the window
  6196. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6197. # get the document() of the TextEditor
  6198. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6199. # create a Text Cursor based on the searched line
  6200. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6201. # set cursor of the code editor with the cursor at the searcehd line
  6202. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6203. def on_filenewscript(self, silent=False):
  6204. """
  6205. Will create a new script file and open it in the Code Editor
  6206. :param silent: if True will not display status messages
  6207. :return: None
  6208. """
  6209. if silent is False:
  6210. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6211. # delete the absolute and relative position and messages in the infobar
  6212. self.ui.position_label.setText("")
  6213. # self.ui.rel_position_label.setText("")
  6214. self.app_obj.new_script_object()
  6215. # script_text = script_obj.source_file
  6216. #
  6217. # self.proc_container.view.set_busy(_("Loading..."))
  6218. # script_obj.script_editor_tab.t_frame.hide()
  6219. #
  6220. # script_obj.script_editor_tab.t_frame.show()
  6221. # self.proc_container.view.set_idle()
  6222. def on_fileopenscript(self, name=None, silent=False):
  6223. """
  6224. Will open a Tcl script file into the Code Editor
  6225. :param silent: if True will not display status messages
  6226. :param name: name of a Tcl script file to open
  6227. :return: None
  6228. """
  6229. self.defaults.report_usage("on_fileopenscript")
  6230. App.log.debug("on_fileopenscript()")
  6231. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6232. "All Files (*.*)"
  6233. if name:
  6234. filenames = [name]
  6235. else:
  6236. try:
  6237. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6238. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6239. except TypeError:
  6240. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6241. if len(filenames) == 0:
  6242. if silent is False:
  6243. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6244. else:
  6245. for filename in filenames:
  6246. if filename != '':
  6247. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6248. def on_fileopenscript_example(self, name=None, silent=False):
  6249. """
  6250. Will open a Tcl script file into the Code Editor
  6251. :param silent: if True will not display status messages
  6252. :param name: name of a Tcl script file to open
  6253. :return:
  6254. """
  6255. self.defaults.report_usage("on_fileopenscript_example")
  6256. log.debug("on_fileopenscript_example()")
  6257. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6258. "All Files (*.*)"
  6259. # test if the app was frozen and choose the path for the configuration file
  6260. if getattr(sys, "frozen", False) is True:
  6261. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6262. else:
  6263. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6264. if name:
  6265. filenames = [name]
  6266. else:
  6267. try:
  6268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6269. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6270. except TypeError:
  6271. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6272. if len(filenames) == 0:
  6273. if silent is False:
  6274. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6275. else:
  6276. for filename in filenames:
  6277. if filename != '':
  6278. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6279. def on_filerunscript(self, name=None, silent=False):
  6280. """
  6281. File menu callback for loading and running a TCL script.
  6282. :param silent: if True will not display status messages
  6283. :param name: name of a Tcl script file to be run by FlatCAM
  6284. :return: None
  6285. """
  6286. self.defaults.report_usage("on_filerunscript")
  6287. App.log.debug("on_file_runscript()")
  6288. if name:
  6289. filename = name
  6290. if self.cmd_line_headless != 1:
  6291. self.splash.showMessage('%s: %ssec\n%s' %
  6292. (_("Canvas initialization started.\n"
  6293. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6294. _("Executing ScriptObject file.")
  6295. ),
  6296. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6297. color=QtGui.QColor("gray"))
  6298. else:
  6299. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6300. "All Files (*.*)"
  6301. try:
  6302. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6303. directory=self.get_last_folder(), filter=_filter_)
  6304. except TypeError:
  6305. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6306. # The Qt methods above will return a QString which can cause problems later.
  6307. # So far json.dump() will fail to serialize it.
  6308. filename = str(filename)
  6309. if filename == "":
  6310. if silent is False:
  6311. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6312. else:
  6313. if self.cmd_line_headless != 1:
  6314. if self.ui.shell_dock.isHidden():
  6315. self.ui.shell_dock.show()
  6316. try:
  6317. with open(filename, "r") as tcl_script:
  6318. cmd_line_shellfile_content = tcl_script.read()
  6319. if self.cmd_line_headless != 1:
  6320. self.shell.exec_command(cmd_line_shellfile_content)
  6321. else:
  6322. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6323. if silent is False:
  6324. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6325. except Exception as e:
  6326. log.debug("App.on_filerunscript() -> %s" % str(e))
  6327. sys.exit(2)
  6328. def on_file_saveproject(self, silent=False):
  6329. """
  6330. Callback for menu item File->Save Project. Saves the project to
  6331. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6332. if set to None. The project is saved by calling ``self.save_project()``.
  6333. :param silent: if True will not display status messages
  6334. :return: None
  6335. """
  6336. self.defaults.report_usage("on_file_saveproject")
  6337. if self.project_filename is None:
  6338. self.on_file_saveprojectas()
  6339. else:
  6340. self.worker_task.emit({'fcn': self.save_project,
  6341. 'params': [self.project_filename, silent]})
  6342. if self.defaults["global_open_style"] is False:
  6343. self.file_opened.emit("project", self.project_filename)
  6344. self.file_saved.emit("project", self.project_filename)
  6345. self.set_ui_title(name=self.project_filename)
  6346. self.should_we_save = False
  6347. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6348. """
  6349. Callback for menu item File->Save Project As... Opens a file
  6350. chooser and saves the project to the given file via
  6351. ``self.save_project()``.
  6352. :param make_copy if to be create a copy of the project; boolean
  6353. :param use_thread: if to be run in a separate thread; boolean
  6354. :param quit_action: if to be followed by quiting the application; boolean
  6355. :return: None
  6356. """
  6357. self.defaults.report_usage("on_file_saveprojectas")
  6358. self.date = str(datetime.today()).rpartition('.')[0]
  6359. self.date = ''.join(c for c in self.date if c not in ':-')
  6360. self.date = self.date.replace(' ', '_')
  6361. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6362. try:
  6363. filename, _f = FCFileSaveDialog.get_saved_filename(
  6364. caption=_("Save Project As ..."),
  6365. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6366. proj=_("Project")),
  6367. ext_filter=filter_
  6368. )
  6369. except TypeError:
  6370. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6371. filename = str(filename)
  6372. if filename == '':
  6373. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6374. return
  6375. if use_thread is True:
  6376. self.worker_task.emit({'fcn': self.save_project,
  6377. 'params': [filename, quit_action]})
  6378. else:
  6379. self.save_project(filename, quit_action)
  6380. # self.save_project(filename)
  6381. if self.defaults["global_open_style"] is False:
  6382. self.file_opened.emit("project", filename)
  6383. self.file_saved.emit("project", filename)
  6384. if not make_copy:
  6385. self.project_filename = filename
  6386. self.set_ui_title(name=self.project_filename)
  6387. self.should_we_save = False
  6388. def on_file_save_objects_pdf(self, use_thread=True):
  6389. self.date = str(datetime.today()).rpartition('.')[0]
  6390. self.date = ''.join(c for c in self.date if c not in ':-')
  6391. self.date = self.date.replace(' ', '_')
  6392. try:
  6393. obj_selection = self.collection.get_selected()
  6394. if len(obj_selection) == 1:
  6395. obj_name = str(obj_selection[0].options['name'])
  6396. else:
  6397. obj_name = _("FlatCAM objects print")
  6398. except AttributeError as err:
  6399. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6400. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6401. return
  6402. if not obj_selection:
  6403. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6404. return
  6405. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6406. try:
  6407. filename, _f = FCFileSaveDialog.get_saved_filename(
  6408. caption=_("Save Object as PDF ..."),
  6409. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6410. obj_name=obj_name,
  6411. date=self.date),
  6412. ext_filter=filter_
  6413. )
  6414. except TypeError:
  6415. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6416. filename = str(filename)
  6417. if filename == '':
  6418. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6419. return
  6420. if use_thread is True:
  6421. self.proc_container.new(_("Printing PDF ... Please wait."))
  6422. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6423. else:
  6424. self.save_pdf(filename, obj_selection)
  6425. # self.save_project(filename)
  6426. if self.defaults["global_open_style"] is False:
  6427. self.file_opened.emit("pdf", filename)
  6428. self.file_saved.emit("pdf", filename)
  6429. def save_pdf(self, file_name, obj_selection):
  6430. p_size = self.defaults['global_workspaceT']
  6431. orientation = self.defaults['global_workspace_orientation']
  6432. color = 'black'
  6433. transparency_level = 1.0
  6434. self.pagesize = {}
  6435. self.pagesize.update(
  6436. {
  6437. 'Bounds': None,
  6438. 'A0': (841 * mm, 1189 * mm),
  6439. 'A1': (594 * mm, 841 * mm),
  6440. 'A2': (420 * mm, 594 * mm),
  6441. 'A3': (297 * mm, 420 * mm),
  6442. 'A4': (210 * mm, 297 * mm),
  6443. 'A5': (148 * mm, 210 * mm),
  6444. 'A6': (105 * mm, 148 * mm),
  6445. 'A7': (74 * mm, 105 * mm),
  6446. 'A8': (52 * mm, 74 * mm),
  6447. 'A9': (37 * mm, 52 * mm),
  6448. 'A10': (26 * mm, 37 * mm),
  6449. 'B0': (1000 * mm, 1414 * mm),
  6450. 'B1': (707 * mm, 1000 * mm),
  6451. 'B2': (500 * mm, 707 * mm),
  6452. 'B3': (353 * mm, 500 * mm),
  6453. 'B4': (250 * mm, 353 * mm),
  6454. 'B5': (176 * mm, 250 * mm),
  6455. 'B6': (125 * mm, 176 * mm),
  6456. 'B7': (88 * mm, 125 * mm),
  6457. 'B8': (62 * mm, 88 * mm),
  6458. 'B9': (44 * mm, 62 * mm),
  6459. 'B10': (31 * mm, 44 * mm),
  6460. 'C0': (917 * mm, 1297 * mm),
  6461. 'C1': (648 * mm, 917 * mm),
  6462. 'C2': (458 * mm, 648 * mm),
  6463. 'C3': (324 * mm, 458 * mm),
  6464. 'C4': (229 * mm, 324 * mm),
  6465. 'C5': (162 * mm, 229 * mm),
  6466. 'C6': (114 * mm, 162 * mm),
  6467. 'C7': (81 * mm, 114 * mm),
  6468. 'C8': (57 * mm, 81 * mm),
  6469. 'C9': (40 * mm, 57 * mm),
  6470. 'C10': (28 * mm, 40 * mm),
  6471. # American paper sizes
  6472. 'LETTER': (8.5 * inch, 11 * inch),
  6473. 'LEGAL': (8.5 * inch, 14 * inch),
  6474. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6475. # From https://en.wikipedia.org/wiki/Paper_size
  6476. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6477. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6478. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6479. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6480. 'LEDGER': (17 * inch, 11 * inch),
  6481. }
  6482. )
  6483. exported_svg = []
  6484. for obj in obj_selection:
  6485. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6486. scale_factor_x=None, scale_factor_y=None,
  6487. skew_factor_x=None, skew_factor_y=None,
  6488. mirror=None)
  6489. if obj.kind.lower() == 'gerber':
  6490. # color = self.defaults["gerber_plot_fill"][:-2]
  6491. color = obj.fill_color[:-2]
  6492. elif obj.kind.lower() == 'excellon':
  6493. color = '#C40000'
  6494. elif obj.kind.lower() == 'geometry':
  6495. color = self.defaults["global_draw_color"]
  6496. # Change the attributes of the exported SVG
  6497. # We don't need stroke-width
  6498. # We set opacity to maximum
  6499. # We set the colour to WHITE
  6500. root = ET.fromstring(svg_obj)
  6501. for child in root:
  6502. child.set('fill', str(color))
  6503. child.set('opacity', str(transparency_level))
  6504. child.set('stroke', str(color))
  6505. exported_svg.append(ET.tostring(root))
  6506. xmin = Inf
  6507. ymin = Inf
  6508. xmax = -Inf
  6509. ymax = -Inf
  6510. for obj in obj_selection:
  6511. try:
  6512. gxmin, gymin, gxmax, gymax = obj.bounds()
  6513. xmin = min([xmin, gxmin])
  6514. ymin = min([ymin, gymin])
  6515. xmax = max([xmax, gxmax])
  6516. ymax = max([ymax, gymax])
  6517. except Exception as e:
  6518. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6519. # Determine bounding area for svg export
  6520. bounds = [xmin, ymin, xmax, ymax]
  6521. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6522. # This contain the measure units
  6523. uom = obj_selection[0].units.lower()
  6524. # Define a boundary around SVG of about 1.0mm (~39mils)
  6525. if uom in "mm":
  6526. boundary = 1.0
  6527. else:
  6528. boundary = 0.0393701
  6529. # Convert everything to strings for use in the xml doc
  6530. svgwidth = str(size[0] + (2 * boundary))
  6531. svgheight = str(size[1] + (2 * boundary))
  6532. minx = str(bounds[0] - boundary)
  6533. miny = str(bounds[1] + boundary + size[1])
  6534. # Add a SVG Header and footer to the svg output from shapely
  6535. # The transform flips the Y Axis so that everything renders
  6536. # properly within svg apps such as inkscape
  6537. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6538. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6539. svg_header += 'width="' + svgwidth + uom + '" '
  6540. svg_header += 'height="' + svgheight + uom + '" '
  6541. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6542. svg_header += '>'
  6543. svg_header += '<g transform="scale(1,-1)">'
  6544. svg_footer = '</g> </svg>'
  6545. svg_elem = str(svg_header)
  6546. for svg_item in exported_svg:
  6547. svg_elem += str(svg_item)
  6548. svg_elem += str(svg_footer)
  6549. # Parse the xml through a xml parser just to add line feeds
  6550. # and to make it look more pretty for the output
  6551. doc = parse_xml_string(svg_elem)
  6552. doc_final = doc.toprettyxml()
  6553. try:
  6554. if self.defaults['units'].upper() == 'IN':
  6555. unit = inch
  6556. else:
  6557. unit = mm
  6558. doc_final = StringIO(doc_final)
  6559. drawing = svg2rlg(doc_final)
  6560. if p_size == 'Bounds':
  6561. renderPDF.drawToFile(drawing, file_name)
  6562. else:
  6563. if orientation == 'p':
  6564. page_size = portrait(self.pagesize[p_size])
  6565. else:
  6566. page_size = landscape(self.pagesize[p_size])
  6567. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6568. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6569. renderPDF.draw(drawing, my_canvas, 0, 0)
  6570. my_canvas.save()
  6571. except Exception as e:
  6572. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6573. return 'fail'
  6574. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6575. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6576. """
  6577. Exports a Geometry Object to an SVG file.
  6578. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6579. :param filename: Path to the SVG file to save to.
  6580. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6581. :return:
  6582. """
  6583. self.defaults.report_usage("export_svg()")
  6584. if filename is None:
  6585. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6586. is not None else self.defaults["global_last_folder"]
  6587. self.log.debug("export_svg()")
  6588. try:
  6589. obj = self.collection.get_by_name(str(obj_name))
  6590. except Exception:
  6591. # TODO: The return behavior has not been established... should raise exception?
  6592. return "Could not retrieve object: %s" % obj_name
  6593. with self.proc_container.new(_("Exporting SVG")) as proc:
  6594. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6595. # Determine bounding area for svg export
  6596. bounds = obj.bounds()
  6597. size = obj.size()
  6598. # Convert everything to strings for use in the xml doc
  6599. svgwidth = str(size[0])
  6600. svgheight = str(size[1])
  6601. minx = str(bounds[0])
  6602. miny = str(bounds[1] - size[1])
  6603. uom = obj.units.lower()
  6604. # Add a SVG Header and footer to the svg output from shapely
  6605. # The transform flips the Y Axis so that everything renders
  6606. # properly within svg apps such as inkscape
  6607. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6608. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6609. svg_header += 'width="' + svgwidth + uom + '" '
  6610. svg_header += 'height="' + svgheight + uom + '" '
  6611. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6612. svg_header += '<g transform="scale(1,-1)">'
  6613. svg_footer = '</g> </svg>'
  6614. svg_elem = svg_header + exported_svg + svg_footer
  6615. # Parse the xml through a xml parser just to add line feeds
  6616. # and to make it look more pretty for the output
  6617. svgcode = parse_xml_string(svg_elem)
  6618. svgcode = svgcode.toprettyxml()
  6619. try:
  6620. with open(filename, 'w') as fp:
  6621. fp.write(svgcode)
  6622. except PermissionError:
  6623. self.inform.emit('[WARNING] %s' %
  6624. _("Permission denied, saving not possible.\n"
  6625. "Most likely another app is holding the file open and not accessible."))
  6626. return 'fail'
  6627. if self.defaults["global_open_style"] is False:
  6628. self.file_opened.emit("SVG", filename)
  6629. self.file_saved.emit("SVG", filename)
  6630. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6631. def save_source_file(self, obj_name, filename, use_thread=True):
  6632. """
  6633. Exports a FlatCAM Object to an Gerber/Excellon file.
  6634. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6635. :param filename: Path to the Gerber file to save to.
  6636. :param use_thread: if to be run in a separate thread
  6637. :return:
  6638. """
  6639. self.defaults.report_usage("save source file()")
  6640. if filename is None:
  6641. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6642. is not None else self.defaults["global_last_folder"]
  6643. self.log.debug("save source file()")
  6644. obj = self.collection.get_by_name(obj_name)
  6645. file_string = StringIO(obj.source_file)
  6646. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6647. if file_string.getvalue() == '':
  6648. self.inform.emit('[ERROR_NOTCL] %s' %
  6649. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6650. return 'fail'
  6651. try:
  6652. with open(filename, 'w') as file:
  6653. file.writelines('G04*\n')
  6654. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6655. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6656. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6657. file.writelines('G04 Created on : %s*\n' % time_string)
  6658. for line in file_string:
  6659. file.writelines(line)
  6660. except PermissionError:
  6661. self.inform.emit('[WARNING] %s' %
  6662. _("Permission denied, saving not possible.\n"
  6663. "Most likely another app is holding the file open and not accessible."))
  6664. return 'fail'
  6665. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6666. """
  6667. Exports a Excellon Object to an Excellon file.
  6668. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6669. :param filename: Path to the Excellon file to save to.
  6670. :param local_use:
  6671. :param use_thread: if to be run in a separate thread
  6672. :return:
  6673. """
  6674. self.defaults.report_usage("export_excellon()")
  6675. if filename is None:
  6676. if self.defaults["global_last_save_folder"]:
  6677. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6678. else:
  6679. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6680. self.log.debug("export_excellon()")
  6681. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6682. self.defaults["excellon_exp_decimals"]
  6683. )
  6684. if local_use is None:
  6685. try:
  6686. obj = self.collection.get_by_name(str(obj_name))
  6687. except Exception:
  6688. return "Could not retrieve object: %s" % obj_name
  6689. else:
  6690. obj = local_use
  6691. if not isinstance(obj, ExcellonObject):
  6692. self.inform.emit('[ERROR_NOTCL] %s' %
  6693. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6694. return
  6695. # updated units
  6696. eunits = self.defaults["excellon_exp_units"]
  6697. ewhole = self.defaults["excellon_exp_integer"]
  6698. efract = self.defaults["excellon_exp_decimals"]
  6699. ezeros = self.defaults["excellon_exp_zeros"]
  6700. eformat = self.defaults["excellon_exp_format"]
  6701. slot_type = self.defaults["excellon_exp_slot_type"]
  6702. fc_units = self.defaults['units'].upper()
  6703. if fc_units == 'MM':
  6704. factor = 1 if eunits == 'METRIC' else 0.03937
  6705. else:
  6706. factor = 25.4 if eunits == 'METRIC' else 1
  6707. def make_excellon():
  6708. try:
  6709. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6710. header = 'M48\n'
  6711. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6712. (str(self.version), str(self.version_date))
  6713. header += ';Filename: %s' % str(obj_name) + '\n'
  6714. header += ';Created on : %s' % time_str + '\n'
  6715. if eformat == 'dec':
  6716. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6717. header += eunits + '\n'
  6718. for tool in obj.tools:
  6719. if eunits == 'METRIC':
  6720. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6721. tool=str(tool),
  6722. dec=2)
  6723. else:
  6724. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6725. tool=str(tool),
  6726. dec=4)
  6727. else:
  6728. if ezeros == 'LZ':
  6729. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6730. form='ndec', e_zeros='LZ', factor=factor,
  6731. slot_type=slot_type)
  6732. header += '%s,%s\n' % (eunits, 'LZ')
  6733. header += format_exc
  6734. for tool in obj.tools:
  6735. if eunits == 'METRIC':
  6736. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6737. tool=str(tool),
  6738. dec=2)
  6739. else:
  6740. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6741. tool=str(tool),
  6742. dec=4)
  6743. else:
  6744. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6745. form='ndec', e_zeros='TZ', factor=factor,
  6746. slot_type=slot_type)
  6747. header += '%s,%s\n' % (eunits, 'TZ')
  6748. header += format_exc
  6749. for tool in obj.tools:
  6750. if eunits == 'METRIC':
  6751. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6752. tool=str(tool),
  6753. dec=2)
  6754. else:
  6755. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6756. tool=str(tool),
  6757. dec=4)
  6758. header += '%\n'
  6759. footer = 'M30\n'
  6760. exported_excellon = header
  6761. exported_excellon += excellon_code
  6762. exported_excellon += footer
  6763. if local_use is None:
  6764. try:
  6765. with open(filename, 'w') as fp:
  6766. fp.write(exported_excellon)
  6767. except PermissionError:
  6768. self.inform.emit('[WARNING] %s' %
  6769. _("Permission denied, saving not possible.\n"
  6770. "Most likely another app is holding the file open and not accessible."))
  6771. return 'fail'
  6772. if self.defaults["global_open_style"] is False:
  6773. self.file_opened.emit("Excellon", filename)
  6774. self.file_saved.emit("Excellon", filename)
  6775. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6776. else:
  6777. return exported_excellon
  6778. except Exception as e:
  6779. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6780. return 'fail'
  6781. if use_thread is True:
  6782. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6783. def job_thread_exc(app_obj):
  6784. ret = make_excellon()
  6785. if ret == 'fail':
  6786. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6787. return
  6788. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6789. else:
  6790. eret = make_excellon()
  6791. if eret == 'fail':
  6792. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6793. return 'fail'
  6794. if local_use is not None:
  6795. return eret
  6796. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6797. """
  6798. Exports a Gerber Object to an Gerber file.
  6799. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6800. :param filename: Path to the Gerber file to save to.
  6801. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6802. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6803. :param use_thread: if to be run in a separate thread
  6804. :return:
  6805. """
  6806. self.defaults.report_usage("export_gerber()")
  6807. if filename is None:
  6808. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6809. is not None else self.defaults["global_last_folder"]
  6810. self.log.debug("export_gerber()")
  6811. if local_use is None:
  6812. try:
  6813. obj = self.collection.get_by_name(str(obj_name))
  6814. except Exception:
  6815. return "Could not retrieve object: %s" % obj_name
  6816. else:
  6817. obj = local_use
  6818. # updated units
  6819. gunits = self.defaults["gerber_exp_units"]
  6820. gwhole = self.defaults["gerber_exp_integer"]
  6821. gfract = self.defaults["gerber_exp_decimals"]
  6822. gzeros = self.defaults["gerber_exp_zeros"]
  6823. fc_units = self.defaults['units'].upper()
  6824. if fc_units == 'MM':
  6825. factor = 1 if gunits == 'MM' else 0.03937
  6826. else:
  6827. factor = 25.4 if gunits == 'MM' else 1
  6828. def make_gerber():
  6829. try:
  6830. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6831. header = 'G04*\n'
  6832. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6833. (str(self.version), str(self.version_date))
  6834. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6835. header += 'G04 Created on : %s*' % time_str + '\n'
  6836. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6837. header += "%MO{units}*%\n".format(units=gunits)
  6838. for apid in obj.apertures:
  6839. if obj.apertures[apid]['type'] == 'C':
  6840. header += "%ADD{apid}{type},{size}*%\n".format(
  6841. apid=str(apid),
  6842. type='C',
  6843. size=(factor * obj.apertures[apid]['size'])
  6844. )
  6845. elif obj.apertures[apid]['type'] == 'R':
  6846. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6847. apid=str(apid),
  6848. type='R',
  6849. width=(factor * obj.apertures[apid]['width']),
  6850. height=(factor * obj.apertures[apid]['height'])
  6851. )
  6852. elif obj.apertures[apid]['type'] == 'O':
  6853. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6854. apid=str(apid),
  6855. type='O',
  6856. width=(factor * obj.apertures[apid]['width']),
  6857. height=(factor * obj.apertures[apid]['height'])
  6858. )
  6859. header += '\n'
  6860. # obsolete units but some software may need it
  6861. if gunits == 'IN':
  6862. header += 'G70*\n'
  6863. else:
  6864. header += 'G71*\n'
  6865. # Absolute Mode
  6866. header += 'G90*\n'
  6867. header += 'G01*\n'
  6868. # positive polarity
  6869. header += '%LPD*%\n'
  6870. footer = 'M02*\n'
  6871. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6872. exported_gerber = header
  6873. exported_gerber += gerber_code
  6874. exported_gerber += footer
  6875. if local_use is None:
  6876. try:
  6877. with open(filename, 'w') as fp:
  6878. fp.write(exported_gerber)
  6879. except PermissionError:
  6880. self.inform.emit('[WARNING] %s' %
  6881. _("Permission denied, saving not possible.\n"
  6882. "Most likely another app is holding the file open and not accessible."))
  6883. return 'fail'
  6884. if self.defaults["global_open_style"] is False:
  6885. self.file_opened.emit("Gerber", filename)
  6886. self.file_saved.emit("Gerber", filename)
  6887. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6888. else:
  6889. return exported_gerber
  6890. except Exception as e:
  6891. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6892. return 'fail'
  6893. if use_thread is True:
  6894. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6895. def job_thread_grb(app_obj):
  6896. ret = make_gerber()
  6897. if ret == 'fail':
  6898. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6899. return
  6900. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6901. else:
  6902. gret = make_gerber()
  6903. if gret == 'fail':
  6904. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6905. return 'fail'
  6906. if local_use is not None:
  6907. return gret
  6908. def export_dxf(self, obj_name, filename, use_thread=True):
  6909. """
  6910. Exports a Geometry Object to an DXF file.
  6911. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6912. :param filename: Path to the DXF file to save to.
  6913. :param use_thread: if to be run in a separate thread
  6914. :return:
  6915. """
  6916. self.defaults.report_usage("export_dxf()")
  6917. if filename is None:
  6918. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6919. is not None else self.defaults["global_last_folder"]
  6920. self.log.debug("export_dxf()")
  6921. try:
  6922. obj = self.collection.get_by_name(str(obj_name))
  6923. except Exception:
  6924. # TODO: The return behavior has not been established... should raise exception?
  6925. return "Could not retrieve object: %s" % obj_name
  6926. def make_dxf():
  6927. try:
  6928. dxf_code = obj.export_dxf()
  6929. dxf_code.saveas(filename)
  6930. if self.defaults["global_open_style"] is False:
  6931. self.file_opened.emit("DXF", filename)
  6932. self.file_saved.emit("DXF", filename)
  6933. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6934. except Exception:
  6935. return 'fail'
  6936. if use_thread is True:
  6937. with self.proc_container.new(_("Exporting DXF")) as proc:
  6938. def job_thread_exc(app_obj):
  6939. ret_dxf_val = make_dxf()
  6940. if ret_dxf_val == 'fail':
  6941. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6942. return
  6943. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6944. else:
  6945. ret = make_dxf()
  6946. if ret == 'fail':
  6947. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6948. return
  6949. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6950. """
  6951. Adds a new Geometry Object to the projects and populates
  6952. it with shapes extracted from the SVG file.
  6953. :param plot: If True then the resulting object will be plotted on canvas
  6954. :param filename: Path to the SVG file.
  6955. :param geo_type: Type of FlatCAM object that will be created from SVG
  6956. :param outname: The name given to the resulting FlatCAM object
  6957. :return:
  6958. """
  6959. self.defaults.report_usage("import_svg()")
  6960. log.debug("App.import_svg()")
  6961. obj_type = ""
  6962. if geo_type is None or geo_type == "geometry":
  6963. obj_type = "geometry"
  6964. elif geo_type == "gerber":
  6965. obj_type = "gerber"
  6966. else:
  6967. self.inform.emit('[ERROR_NOTCL] %s' %
  6968. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6969. return
  6970. units = self.defaults['units'].upper()
  6971. def obj_init(geo_obj, app_obj):
  6972. geo_obj.import_svg(filename, obj_type, units=units)
  6973. geo_obj.multigeo = False
  6974. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6975. with self.proc_container.new(_("Importing SVG")) as proc:
  6976. # Object name
  6977. name = outname or filename.split('/')[-1].split('\\')[-1]
  6978. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6979. if ret == 'fail':
  6980. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6981. return 'fail'
  6982. # Register recent file
  6983. self.file_opened.emit("svg", filename)
  6984. # appGUI feedback
  6985. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6986. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6987. """
  6988. Adds a new Geometry Object to the projects and populates
  6989. it with shapes extracted from the DXF file.
  6990. :param filename: Path to the DXF file.
  6991. :param geo_type: Type of FlatCAM object that will be created from DXF
  6992. :param outname: Name for the imported Geometry
  6993. :param plot: If True then the resulting object will be plotted on canvas
  6994. :return:
  6995. """
  6996. self.defaults.report_usage("import_dxf()")
  6997. obj_type = ""
  6998. if geo_type is None or geo_type == "geometry":
  6999. obj_type = "geometry"
  7000. elif geo_type == "gerber":
  7001. obj_type = geo_type
  7002. else:
  7003. self.inform.emit('[ERROR_NOTCL] %s' %
  7004. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7005. return
  7006. units = self.defaults['units'].upper()
  7007. def obj_init(geo_obj, app_obj):
  7008. geo_obj.import_dxf(filename, obj_type, units=units)
  7009. geo_obj.multigeo = False
  7010. with self.proc_container.new(_("Importing DXF")):
  7011. # Object name
  7012. name = outname or filename.split('/')[-1].split('\\')[-1]
  7013. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7014. if ret == 'fail':
  7015. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7016. return 'fail'
  7017. # Register recent file
  7018. self.file_opened.emit("dxf", filename)
  7019. # appGUI feedback
  7020. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7021. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7022. """
  7023. Opens a Gerber file, parses it and creates a new object for
  7024. it in the program. Thread-safe.
  7025. :param outname: Name of the resulting object. None causes the
  7026. name to be that of the file. Str.
  7027. :param filename: Gerber file filename
  7028. :type filename: str
  7029. :param plot: boolean, to plot or not the resulting object
  7030. :param from_tcl: True if run from Tcl Shell
  7031. :return: None
  7032. """
  7033. # How the object should be initialized
  7034. def obj_init(gerber_obj, app_obj):
  7035. assert isinstance(gerber_obj, GerberObject), \
  7036. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7037. # Opening the file happens here
  7038. try:
  7039. gerber_obj.parse_file(filename)
  7040. except IOError:
  7041. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7042. return "fail"
  7043. except ParseError as err:
  7044. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7045. app_obj.log.error(str(err))
  7046. return "fail"
  7047. except Exception as e:
  7048. log.debug("App.open_gerber() --> %s" % str(e))
  7049. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7050. msg += traceback.format_exc()
  7051. app_obj.inform.emit(msg)
  7052. return "fail"
  7053. if gerber_obj.is_empty():
  7054. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7055. _("Object is not Gerber file or empty. Aborting object creation."))
  7056. return "fail"
  7057. App.log.debug("open_gerber()")
  7058. with self.proc_container.new(_("Opening Gerber")):
  7059. # Object name
  7060. name = outname or filename.split('/')[-1].split('\\')[-1]
  7061. # # ## Object creation # ##
  7062. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7063. if ret_val == 'fail':
  7064. if from_tcl:
  7065. filename = self.defaults['global_tcl_path'] + '/' + name
  7066. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7067. if ret_val == 'fail':
  7068. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7069. return 'fail'
  7070. # Register recent file
  7071. self.file_opened.emit("gerber", filename)
  7072. # appGUI feedback
  7073. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7074. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7075. """
  7076. Opens an Excellon file, parses it and creates a new object for
  7077. it in the program. Thread-safe.
  7078. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7079. :param filename: Excellon file filename
  7080. :type filename: str
  7081. :param plot: boolean, to plot or not the resulting object
  7082. :param from_tcl: True if run from Tcl Shell
  7083. :return: None
  7084. """
  7085. App.log.debug("open_excellon()")
  7086. # How the object should be initialized
  7087. def obj_init(excellon_obj, app_obj):
  7088. try:
  7089. ret = excellon_obj.parse_file(filename=filename)
  7090. if ret == "fail":
  7091. log.debug("Excellon parsing failed.")
  7092. self.inform.emit('[ERROR_NOTCL] %s' %
  7093. _("This is not Excellon file."))
  7094. return "fail"
  7095. except IOError:
  7096. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7097. (_("Cannot open file"), filename))
  7098. log.debug("Could not open Excellon object.")
  7099. return "fail"
  7100. except Exception:
  7101. msg = '[ERROR_NOTCL] %s' % \
  7102. _("An internal error has occurred. See shell.\n")
  7103. msg += traceback.format_exc()
  7104. app_obj.inform.emit(msg)
  7105. return "fail"
  7106. ret = excellon_obj.create_geometry()
  7107. if ret == 'fail':
  7108. log.debug("Could not create geometry for Excellon object.")
  7109. return "fail"
  7110. for tool in excellon_obj.tools:
  7111. if excellon_obj.tools[tool]['solid_geometry']:
  7112. return
  7113. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7114. return "fail"
  7115. with self.proc_container.new(_("Opening Excellon.")):
  7116. # Object name
  7117. name = outname or filename.split('/')[-1].split('\\')[-1]
  7118. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7119. if ret_val == 'fail':
  7120. if from_tcl:
  7121. filename = self.defaults['global_tcl_path'] + '/' + name
  7122. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7123. if ret_val == 'fail':
  7124. self.inform.emit('[ERROR_NOTCL] %s' %
  7125. _('Open Excellon file failed. Probable not an Excellon file.'))
  7126. return
  7127. # Register recent file
  7128. self.file_opened.emit("excellon", filename)
  7129. # appGUI feedback
  7130. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7131. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7132. """
  7133. Opens a G-gcode file, parses it and creates a new object for
  7134. it in the program. Thread-safe.
  7135. :param filename: G-code file filename
  7136. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7137. :param force_parsing:
  7138. :param plot: If True plot the object on canvas
  7139. :param from_tcl: True if run from Tcl Shell
  7140. :return: None
  7141. """
  7142. App.log.debug("open_gcode()")
  7143. # How the object should be initialized
  7144. def obj_init(job_obj, app_obj_):
  7145. """
  7146. :param job_obj: the resulting object
  7147. :type app_obj_: App
  7148. """
  7149. assert isinstance(app_obj_, App), \
  7150. "Initializer expected App, got %s" % type(app_obj_)
  7151. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7152. try:
  7153. f = open(filename)
  7154. gcode = f.read()
  7155. f.close()
  7156. except IOError:
  7157. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7158. return "fail"
  7159. job_obj.gcode = gcode
  7160. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7161. if gcode_ret == "fail":
  7162. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7163. return "fail"
  7164. job_obj.create_geometry()
  7165. with self.proc_container.new(_("Opening G-Code.")):
  7166. # Object name
  7167. name = outname or filename.split('/')[-1].split('\\')[-1]
  7168. # New object creation and file processing
  7169. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7170. if ret_val == 'fail':
  7171. if from_tcl:
  7172. filename = self.defaults['global_tcl_path'] + '/' + name
  7173. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7174. if ret_val == 'fail':
  7175. self.inform.emit('[ERROR_NOTCL] %s' %
  7176. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7177. "Try to load it from File menu.\n "
  7178. "Attempting to create a FlatCAM CNCJob Object from "
  7179. "G-Code file failed during processing"))
  7180. return "fail"
  7181. # Register recent file
  7182. self.file_opened.emit("cncjob", filename)
  7183. # appGUI feedback
  7184. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7185. def open_hpgl2(self, filename, outname=None):
  7186. """
  7187. Opens a HPGL2 file, parses it and creates a new object for
  7188. it in the program. Thread-safe.
  7189. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7190. :param filename: HPGL2 file filename
  7191. :return: None
  7192. """
  7193. filename = filename
  7194. # How the object should be initialized
  7195. def obj_init(geo_obj, app_obj):
  7196. assert isinstance(geo_obj, GeometryObject), \
  7197. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7198. # Opening the file happens here
  7199. obj = HPGL2(self)
  7200. try:
  7201. HPGL2.parse_file(obj, filename)
  7202. except IOError:
  7203. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7204. return "fail"
  7205. except ParseError as err:
  7206. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7207. app_obj.log.error(str(err))
  7208. return "fail"
  7209. except Exception as e:
  7210. log.debug("App.open_hpgl2() --> %s" % str(e))
  7211. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7212. msg += traceback.format_exc()
  7213. app_obj.inform.emit(msg)
  7214. return "fail"
  7215. geo_obj.multigeo = True
  7216. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7217. geo_obj.tools = deepcopy(obj.tools)
  7218. geo_obj.source_file = deepcopy(obj.source_file)
  7219. del obj
  7220. if not geo_obj.solid_geometry:
  7221. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7222. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7223. return "fail"
  7224. App.log.debug("open_hpgl2()")
  7225. with self.proc_container.new(_("Opening HPGL2")):
  7226. # Object name
  7227. name = outname or filename.split('/')[-1].split('\\')[-1]
  7228. # # ## Object creation # ##
  7229. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7230. if ret == 'fail':
  7231. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7232. return 'fail'
  7233. # Register recent file
  7234. self.file_opened.emit("geometry", filename)
  7235. # appGUI feedback
  7236. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7237. def open_script(self, filename, outname=None, silent=False):
  7238. """
  7239. Opens a Script file, parses it and creates a new object for
  7240. it in the program. Thread-safe.
  7241. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7242. :param filename: Script file filename
  7243. :param silent: If True there will be no messages printed to StatusBar
  7244. :return: None
  7245. """
  7246. def obj_init(script_obj, app_obj):
  7247. assert isinstance(script_obj, ScriptObject), \
  7248. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7249. if silent is False:
  7250. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7251. try:
  7252. script_obj.parse_file(filename)
  7253. except IOError:
  7254. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7255. return "fail"
  7256. except ParseError as err:
  7257. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7258. app_obj.log.error(str(err))
  7259. return "fail"
  7260. except Exception as e:
  7261. log.debug("App.open_script() -> %s" % str(e))
  7262. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7263. msg += traceback.format_exc()
  7264. app_obj.inform.emit(msg)
  7265. return "fail"
  7266. App.log.debug("open_script()")
  7267. with self.proc_container.new(_("Opening TCL Script...")):
  7268. # Object name
  7269. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7270. # Object creation
  7271. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7272. if ret_val == 'fail':
  7273. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7274. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7275. if ret_val == 'fail':
  7276. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7277. return 'fail'
  7278. # Register recent file
  7279. self.file_opened.emit("script", filename)
  7280. # appGUI feedback
  7281. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7282. def open_config_file(self, filename, run_from_arg=None):
  7283. """
  7284. Loads a config file from the specified file.
  7285. :param filename: Name of the file from which to load.
  7286. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7287. :return: None
  7288. """
  7289. App.log.debug("Opening config file: " + filename)
  7290. if run_from_arg:
  7291. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7292. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7293. _("Opening FlatCAM Config file.")),
  7294. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7295. color=QtGui.QColor("gray"))
  7296. # # add the tab if it was closed
  7297. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7298. # # first clear previous text in text editor (if any)
  7299. # self.ui.text_editor_tab.code_editor.clear()
  7300. #
  7301. # # Switch plot_area to CNCJob tab
  7302. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7303. # close the Code editor if already open
  7304. if self.toggle_codeeditor:
  7305. self.on_toggle_code_editor()
  7306. self.on_toggle_code_editor()
  7307. try:
  7308. if filename:
  7309. f = QtCore.QFile(filename)
  7310. if f.open(QtCore.QIODevice.ReadOnly):
  7311. stream = QtCore.QTextStream(f)
  7312. code_edited = stream.readAll()
  7313. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7314. f.close()
  7315. except IOError:
  7316. App.log.error("Failed to open config file: %s" % filename)
  7317. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7318. (_("Failed to open config file"), filename))
  7319. return
  7320. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7321. """
  7322. Loads a project from the specified file.
  7323. 1) Loads and parses file
  7324. 2) Registers the file as recently opened.
  7325. 3) Calls on_file_new()
  7326. 4) Updates options
  7327. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7328. 6) Calls plot_all() if plot=True
  7329. :param filename: Name of the file from which to load.
  7330. :param run_from_arg: True if run for arguments
  7331. :param plot: If True plot all objects in the project
  7332. :param cli: Run from command line
  7333. :param from_tcl: True if run from Tcl Sehll
  7334. :return: None
  7335. """
  7336. App.log.debug("Opening project: " + filename)
  7337. # block autosaving while a project is loaded
  7338. self.block_autosave = True
  7339. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7340. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7341. if cli is None:
  7342. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7343. if run_from_arg:
  7344. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7345. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7346. _("Opening FlatCAM Project file.")),
  7347. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7348. color=QtGui.QColor("gray"))
  7349. # Open and parse an uncompressed Project file
  7350. try:
  7351. f = open(filename, 'r')
  7352. except IOError:
  7353. if from_tcl:
  7354. name = filename.split('/')[-1].split('\\')[-1]
  7355. filename = self.defaults['global_tcl_path'] + '/' + name
  7356. try:
  7357. f = open(filename, 'r')
  7358. except IOError:
  7359. log.error("Failed to open project file: %s" % filename)
  7360. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7361. return
  7362. else:
  7363. log.error("Failed to open project file: %s" % filename)
  7364. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7365. return
  7366. try:
  7367. d = json.load(f, object_hook=dict2obj)
  7368. except Exception as e:
  7369. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7370. (filename, str(e)))
  7371. f.close()
  7372. # Open and parse a compressed Project file
  7373. try:
  7374. with lzma.open(filename) as f:
  7375. file_content = f.read().decode('utf-8')
  7376. d = json.loads(file_content, object_hook=dict2obj)
  7377. except Exception as e:
  7378. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7379. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7380. return
  7381. # Clear the current project
  7382. # # NOT THREAD SAFE # ##
  7383. if run_from_arg is True:
  7384. pass
  7385. elif cli is True:
  7386. self.delete_selection_shape()
  7387. else:
  7388. self.on_file_new()
  7389. # Project options
  7390. self.options.update(d['options'])
  7391. self.project_filename = filename
  7392. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7393. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7394. if cli is None:
  7395. self.set_screen_units(self.options["units"])
  7396. # Re create objects
  7397. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7398. for obj in d['objs']:
  7399. try:
  7400. def obj_init(obj_inst, app_inst):
  7401. obj_inst.from_dict(obj)
  7402. App.log.debug("Recreating from opened project an %s object: %s" %
  7403. (obj['kind'].capitalize(), obj['options']['name']))
  7404. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7405. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7406. if cli is None:
  7407. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7408. obj['kind'].upper(),
  7409. obj['options']['name']
  7410. )
  7411. )
  7412. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7413. except Exception as e:
  7414. print('App.open_project() --> ' + str(e))
  7415. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7416. self.should_we_save = False
  7417. self.file_opened.emit("project", filename)
  7418. # restore autosaving after a project was loaded
  7419. self.block_autosave = False
  7420. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7421. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7422. if cli is None:
  7423. self.set_ui_title(name=self.project_filename)
  7424. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7425. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7426. """
  7427. Re-generates all plots from all objects.
  7428. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7429. :param muted: if True don't print messages
  7430. :param use_thread: if True will use threading for plotting the objects
  7431. :return: None
  7432. """
  7433. self.log.debug("Plot_all()")
  7434. if muted is not True:
  7435. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7436. for plot_obj in self.collection.get_list():
  7437. def worker_task(obj):
  7438. with self.proc_container.new("Plotting"):
  7439. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7440. if fit_view is True:
  7441. self.app_obj.object_plotted.emit(obj)
  7442. if use_thread is True:
  7443. # Send to worker
  7444. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7445. else:
  7446. worker_task(plot_obj)
  7447. def register_folder(self, filename):
  7448. """
  7449. Register the last folder used by the app to open something
  7450. :param filename: the last folder is extracted from the filename
  7451. :return: None
  7452. """
  7453. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7454. def register_save_folder(self, filename):
  7455. """
  7456. Register the last folder used by the app to save something
  7457. :param filename: the last folder is extracted from the filename
  7458. :return: None
  7459. """
  7460. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7461. # def set_progress_bar(self, percentage, text=""):
  7462. # """
  7463. # Set a progress bar to a value (percentage)
  7464. #
  7465. # :param percentage: Value set to the progressbar
  7466. # :param text: Not used
  7467. # :return: None
  7468. # """
  7469. # self.ui.progress_bar.setValue(int(percentage))
  7470. def setup_recent_items(self):
  7471. """
  7472. Setup a dictionary with the recent files accessed, organized by type
  7473. :return:
  7474. """
  7475. icons = {
  7476. "gerber": self.resource_location + "/flatcam_icon16.png",
  7477. "excellon": self.resource_location + "/drill16.png",
  7478. 'geometry': self.resource_location + "/geometry16.png",
  7479. "cncjob": self.resource_location + "/cnc16.png",
  7480. "script": self.resource_location + "/script_new24.png",
  7481. "document": self.resource_location + "/notes16_1.png",
  7482. "project": self.resource_location + "/project16.png",
  7483. "svg": self.resource_location + "/geometry16.png",
  7484. "dxf": self.resource_location + "/dxf16.png",
  7485. "pdf": self.resource_location + "/pdf32.png",
  7486. "image": self.resource_location + "/image16.png"
  7487. }
  7488. try:
  7489. image_opener = self.image_tool.import_image
  7490. except AttributeError:
  7491. image_opener = None
  7492. openers = {
  7493. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7494. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7495. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7496. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7497. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7498. "document": None,
  7499. 'project': self.open_project,
  7500. 'svg': self.import_svg,
  7501. 'dxf': self.import_dxf,
  7502. 'image': image_opener,
  7503. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7504. }
  7505. # Open recent file for files
  7506. try:
  7507. f = open(self.data_path + '/recent.json')
  7508. except IOError:
  7509. App.log.error("Failed to load recent item list.")
  7510. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7511. return
  7512. try:
  7513. self.recent = json.load(f)
  7514. except json.errors.JSONDecodeError:
  7515. App.log.error("Failed to parse recent item list.")
  7516. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7517. f.close()
  7518. return
  7519. f.close()
  7520. # Open recent file for projects
  7521. try:
  7522. fp = open(self.data_path + '/recent_projects.json')
  7523. except IOError:
  7524. App.log.error("Failed to load recent project item list.")
  7525. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7526. return
  7527. try:
  7528. self.recent_projects = json.load(fp)
  7529. except json.errors.JSONDecodeError:
  7530. App.log.error("Failed to parse recent project item list.")
  7531. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7532. fp.close()
  7533. return
  7534. fp.close()
  7535. # Closure needed to create callbacks in a loop.
  7536. # Otherwise late binding occurs.
  7537. def make_callback(func, fname):
  7538. def opener():
  7539. func(fname)
  7540. return opener
  7541. def reset_recent_files():
  7542. # Reset menu
  7543. self.ui.recent.clear()
  7544. self.recent = []
  7545. try:
  7546. ff = open(self.data_path + '/recent.json', 'w')
  7547. except IOError:
  7548. App.log.error("Failed to open recent items file for writing.")
  7549. return
  7550. json.dump(self.recent, ff)
  7551. def reset_recent_projects():
  7552. # Reset menu
  7553. self.ui.recent_projects.clear()
  7554. self.recent_projects = []
  7555. try:
  7556. frp = open(self.data_path + '/recent_projects.json', 'w')
  7557. except IOError:
  7558. App.log.error("Failed to open recent projects items file for writing.")
  7559. return
  7560. json.dump(self.recent, frp)
  7561. # Reset menu
  7562. self.ui.recent.clear()
  7563. self.ui.recent_projects.clear()
  7564. # Create menu items for projects
  7565. for recent in self.recent_projects:
  7566. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7567. if recent['kind'] == 'project':
  7568. try:
  7569. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7570. # Attach callback
  7571. o = make_callback(openers[recent["kind"]], recent['filename'])
  7572. action.triggered.connect(o)
  7573. self.ui.recent_projects.addAction(action)
  7574. except KeyError:
  7575. App.log.error("Unsupported file type: %s" % recent["kind"])
  7576. # Last action in Recent Files menu is one that Clear the content
  7577. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7578. (_("Clear Recent projects")), self)
  7579. clear_action_proj.triggered.connect(reset_recent_projects)
  7580. self.ui.recent_projects.addSeparator()
  7581. self.ui.recent_projects.addAction(clear_action_proj)
  7582. # Create menu items for files
  7583. for recent in self.recent:
  7584. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7585. if recent['kind'] != 'project':
  7586. try:
  7587. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7588. # Attach callback
  7589. o = make_callback(openers[recent["kind"]], recent['filename'])
  7590. action.triggered.connect(o)
  7591. self.ui.recent.addAction(action)
  7592. except KeyError:
  7593. App.log.error("Unsupported file type: %s" % recent["kind"])
  7594. # Last action in Recent Files menu is one that Clear the content
  7595. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7596. (_("Clear Recent files")), self)
  7597. clear_action.triggered.connect(reset_recent_files)
  7598. self.ui.recent.addSeparator()
  7599. self.ui.recent.addAction(clear_action)
  7600. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7601. # self.ui.menufilerecent.set_submenu(recent_menu)
  7602. # recent_menu.show_all()
  7603. # self.ui.recent.show()
  7604. self.log.debug("Recent items list has been populated.")
  7605. def setup_component_editor(self):
  7606. """
  7607. Default text for the Selected tab when is not taken by the Object UI.
  7608. :return:
  7609. """
  7610. # label = QtWidgets.QLabel("Choose an item from Project")
  7611. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7612. sel_title = QtWidgets.QTextEdit(
  7613. _('<b>Shortcut Key List</b>'))
  7614. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7615. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7616. f_settings = QSettings("Open Source", "FlatCAM")
  7617. if f_settings.contains("notebook_font_size"):
  7618. fsize = f_settings.value('notebook_font_size', type=int)
  7619. else:
  7620. fsize = 12
  7621. tsize = fsize + int(fsize / 2)
  7622. # selected_text = (_('''
  7623. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7624. # </p>
  7625. #
  7626. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7627. # The normal flow when working in FlatCAM is the following:</span></p>
  7628. #
  7629. # <ol>
  7630. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7631. # file into
  7632. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7633. # even dragging and dropping the files on the appGUI.<br />
  7634. # <br />
  7635. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7636. # drop of the
  7637. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7638. # &nbsp;</li>
  7639. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7640. # and then
  7641. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7642. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7643. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7644. # <br />
  7645. # If the selection of the object is done on the canvas by single click instead, and the
  7646. # <strong>SELECTED TAB</strong>
  7647. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7648. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7649. # it even if it was out of focus.<br />
  7650. # <br />
  7651. # You can change the parameters in this screen and the flow direction is like this:<br />
  7652. # <br />
  7653. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7654. # <strong> Geometry Object
  7655. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7656. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7657. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7658. # </ol>
  7659. #
  7660. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7661. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7662. # <strong>F3</strong>.</span></p>
  7663. #
  7664. # ''').format(fsize=fsize, tsize=tsize))
  7665. selected_text = '''
  7666. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7667. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7668. {s1}</span></p>
  7669. <ol>
  7670. <li><span style="font-size:{fsize}px">{s2}<br />
  7671. <br />
  7672. {s3}</span><br />
  7673. &nbsp;</li>
  7674. <li><span style="font-size:{fsize}px">{s4}<br />
  7675. &nbsp;</li>
  7676. <br />
  7677. <li><span style="font-size:{fsize}px">{s5}<br />
  7678. &nbsp;</li>
  7679. <br />
  7680. <li><span style="font-size:{fsize}px">{s6}<br />
  7681. <br />
  7682. {s7}</span></li>
  7683. </ol>
  7684. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7685. '''.format(
  7686. title=_("Selected Tab - Choose an Item from Project Tab"),
  7687. subtitle=_("Details"),
  7688. s1=_("The normal flow when working with the application is the following:"),
  7689. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7690. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7691. "files on the GUI."),
  7692. s3=_("You can also load a project by double clicking on the project file, "
  7693. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7694. "actions offered within the app."),
  7695. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7696. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7697. "SELECTED TAB will be updated with the object properties according to its kind: "
  7698. "Gerber, Excellon, Geometry or CNCJob object."),
  7699. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7700. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7701. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7702. "the SELECTED TAB and populate it even if it was out of focus."),
  7703. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7704. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7705. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7706. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7707. "(again, done in SELECTED TAB) --> Save GCode."),
  7708. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7709. "or through its own key shortcut: <b>F3</b>."),
  7710. tsize=tsize,
  7711. fsize=fsize
  7712. )
  7713. sel_title.setText(selected_text)
  7714. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7715. self.ui.selected_scroll_area.setWidget(sel_title)
  7716. def setup_obj_classes(self):
  7717. """
  7718. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7719. class.
  7720. :return: None
  7721. """
  7722. FlatCAMObj.app = self
  7723. ObjectCollection.app = self
  7724. Gerber.app = self
  7725. Excellon.app = self
  7726. Geometry.app = self
  7727. CNCjob.app = self
  7728. FCProcess.app = self
  7729. FCProcessContainer.app = self
  7730. OptionsGroupUI.app = self
  7731. def version_check(self):
  7732. """
  7733. Checks for the latest version of the program. Alerts the
  7734. user if theirs is outdated. This method is meant to be run
  7735. in a separate thread.
  7736. :return: None
  7737. """
  7738. self.log.debug("version_check()")
  7739. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7740. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7741. App.version_url,
  7742. str(self.defaults['global_serial']),
  7743. str(self.version),
  7744. str(self.os),
  7745. urllib.parse.urlencode(self.defaults["global_stats"])
  7746. )
  7747. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7748. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7749. # urllib.parse.urlencode(self.defaults["global_stats"])
  7750. else:
  7751. # no_stats dict; just so it won't break things on website
  7752. no_ststs_dict = {}
  7753. no_ststs_dict["global_ststs"] = {}
  7754. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7755. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7756. App.log.debug("Checking for updates @ %s" % full_url)
  7757. # ## Get the data
  7758. try:
  7759. f = urllib.request.urlopen(full_url)
  7760. except Exception:
  7761. # App.log.warning("Failed checking for latest version. Could not connect.")
  7762. self.log.warning("Failed checking for latest version. Could not connect.")
  7763. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7764. return
  7765. try:
  7766. data = json.load(f)
  7767. except Exception as e:
  7768. App.log.error("Could not parse information about latest version.")
  7769. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7770. App.log.debug("json.load(): %s" % str(e))
  7771. f.close()
  7772. return
  7773. f.close()
  7774. # ## Latest version?
  7775. if self.version >= data["version"]:
  7776. App.log.debug("FlatCAM is up to date!")
  7777. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7778. return
  7779. App.log.debug("Newer version available.")
  7780. self.message.emit(
  7781. _("Newer Version Available"),
  7782. '%s<br><br>><b>%s</b><br>%s' % (
  7783. _("There is a newer version of FlatCAM available for download:"),
  7784. str(data["name"]),
  7785. str(data["message"])
  7786. ),
  7787. _("info")
  7788. )
  7789. def on_plotcanvas_setup(self, container=None):
  7790. """
  7791. This is doing the setup for the plot area (canvas).
  7792. :param container: QT Widget where to install the canvas
  7793. :return: None
  7794. """
  7795. if container:
  7796. plot_container = container
  7797. else:
  7798. plot_container = self.ui.right_layout
  7799. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7800. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7801. self.is_legacy = True
  7802. self.defaults["global_graphic_engine"] = "2D"
  7803. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7804. else:
  7805. try:
  7806. self.plotcanvas = PlotCanvas(plot_container, self)
  7807. except Exception as er:
  7808. msg_txt = traceback.format_exc()
  7809. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7810. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7811. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7812. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7813. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7814. msg += msg_txt
  7815. self.inform.emit(msg)
  7816. return 'fail'
  7817. # So it can receive key presses
  7818. self.plotcanvas.native.setFocus()
  7819. if self.is_legacy is False:
  7820. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7821. # Set the mouse button for panning
  7822. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7823. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7824. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7825. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7826. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7827. # Keys over plot enabled
  7828. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7829. if self.defaults['global_cursor_type'] == 'small':
  7830. self.app_cursor = self.plotcanvas.new_cursor()
  7831. else:
  7832. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7833. if self.ui.grid_snap_btn.isChecked():
  7834. self.app_cursor.enabled = True
  7835. else:
  7836. self.app_cursor.enabled = False
  7837. if self.is_legacy is False:
  7838. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7839. else:
  7840. # will use the default Matplotlib axes
  7841. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7842. def on_zoom_fit(self):
  7843. """
  7844. Callback for zoom-fit request. This can be either from the corresponding
  7845. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7846. with axes limits from the geometry bounds of all objects.
  7847. :return: None
  7848. """
  7849. if self.is_legacy is False:
  7850. self.plotcanvas.fit_view()
  7851. else:
  7852. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7853. width = xmax - xmin
  7854. height = ymax - ymin
  7855. xmin -= 0.05 * width
  7856. xmax += 0.05 * width
  7857. ymin -= 0.05 * height
  7858. ymax += 0.05 * height
  7859. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7860. def on_zoom_in(self):
  7861. """
  7862. Callback for zoom-in request.
  7863. :return:
  7864. """
  7865. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7866. def on_zoom_out(self):
  7867. """
  7868. Callback for zoom-out request.
  7869. :return:
  7870. """
  7871. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7872. def disable_all_plots(self):
  7873. self.defaults.report_usage("disable_all_plots()")
  7874. self.disable_plots(self.collection.get_list())
  7875. self.inform.emit('[success] %s' %
  7876. _("All plots disabled."))
  7877. def disable_other_plots(self):
  7878. self.defaults.report_usage("disable_other_plots()")
  7879. self.disable_plots(self.collection.get_non_selected())
  7880. self.inform.emit('[success] %s' %
  7881. _("All non selected plots disabled."))
  7882. def enable_all_plots(self):
  7883. self.defaults.report_usage("enable_all_plots()")
  7884. self.enable_plots(self.collection.get_list())
  7885. self.inform.emit('[success] %s' %
  7886. _("All plots enabled."))
  7887. def on_enable_sel_plots(self):
  7888. log.debug("App.on_enable_sel_plot()")
  7889. object_list = self.collection.get_selected()
  7890. self.enable_plots(objects=object_list)
  7891. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7892. def on_disable_sel_plots(self):
  7893. log.debug("App.on_disable_sel_plot()")
  7894. # self.inform.emit(_("Disabling plots ..."))
  7895. object_list = self.collection.get_selected()
  7896. self.disable_plots(objects=object_list)
  7897. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7898. def enable_plots(self, objects):
  7899. """
  7900. Enable plots
  7901. :param objects: list of Objects to be enabled
  7902. :return:
  7903. """
  7904. log.debug("Enabling plots ...")
  7905. # self.inform.emit(_("Working ..."))
  7906. for obj in objects:
  7907. if obj.options['plot'] is False:
  7908. obj.options.set_change_callback(lambda x: None)
  7909. obj.options['plot'] = True
  7910. try:
  7911. # only the Gerber obj has on_plot_cb_click() method
  7912. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7913. # disable this cb while disconnected,
  7914. # in case the operation takes time the user is not allowed to change it
  7915. obj.ui.plot_cb.setDisabled(True)
  7916. except AttributeError:
  7917. pass
  7918. obj.set_form_item("plot")
  7919. try:
  7920. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7921. obj.ui.plot_cb.setDisabled(False)
  7922. except AttributeError:
  7923. pass
  7924. obj.options.set_change_callback(obj.on_options_change)
  7925. def worker_task(objs):
  7926. with self.proc_container.new(_("Enabling plots ...")):
  7927. for plot_obj in objs:
  7928. # obj.options['plot'] = True
  7929. if isinstance(plot_obj, CNCJobObject):
  7930. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7931. else:
  7932. plot_obj.plot(visible=True)
  7933. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7934. def disable_plots(self, objects):
  7935. """
  7936. Disables plots
  7937. :param objects: list of Objects to be disabled
  7938. :return:
  7939. """
  7940. # if no objects selected then do nothing
  7941. if not self.collection.get_selected():
  7942. return
  7943. log.debug("Disabling plots ...")
  7944. # self.inform.emit(_("Working ..."))
  7945. for obj in objects:
  7946. if obj.options['plot'] is True:
  7947. obj.options.set_change_callback(lambda x: None)
  7948. obj.options['plot'] = False
  7949. try:
  7950. # only the Gerber obj has on_plot_cb_click() method
  7951. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7952. obj.ui.plot_cb.setDisabled(True)
  7953. except AttributeError:
  7954. pass
  7955. obj.set_form_item("plot")
  7956. try:
  7957. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7958. obj.ui.plot_cb.setDisabled(False)
  7959. except AttributeError:
  7960. pass
  7961. obj.options.set_change_callback(obj.on_options_change)
  7962. try:
  7963. self.delete_selection_shape()
  7964. except Exception as e:
  7965. log.debug("App.disable_plots() --> %s" % str(e))
  7966. def worker_task(objs):
  7967. with self.proc_container.new(_("Disabling plots ...")):
  7968. for plot_obj in objs:
  7969. # obj.options['plot'] = True
  7970. if isinstance(plot_obj, CNCJobObject):
  7971. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7972. else:
  7973. plot_obj.plot(visible=False)
  7974. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7975. def toggle_plots(self, objects):
  7976. """
  7977. Toggle plots visibility
  7978. :param objects: list of Objects for which to be toggled the visibility
  7979. :return: None
  7980. """
  7981. # if no objects selected then do nothing
  7982. if not self.collection.get_selected():
  7983. return
  7984. log.debug("Toggling plots ...")
  7985. self.inform.emit(_("Working ..."))
  7986. for obj in objects:
  7987. if obj.options['plot'] is False:
  7988. obj.options['plot'] = True
  7989. else:
  7990. obj.options['plot'] = False
  7991. self.app_obj.plots_updated.emit()
  7992. def clear_plots(self):
  7993. """
  7994. Clear the plots
  7995. :return: None
  7996. """
  7997. objects = self.collection.get_list()
  7998. for obj in objects:
  7999. obj.clear(obj == objects[-1])
  8000. # Clear pool to free memory
  8001. self.clear_pool()
  8002. def on_set_color_action_triggered(self):
  8003. """
  8004. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8005. :return:
  8006. """
  8007. new_color = self.defaults['gerber_plot_fill']
  8008. clicked_action = self.sender()
  8009. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8010. act_name = clicked_action.text()
  8011. sel_obj_list = self.collection.get_selected()
  8012. if not sel_obj_list:
  8013. return
  8014. # a default value, I just chose this one
  8015. alpha_level = 'BF'
  8016. for sel_obj in sel_obj_list:
  8017. if sel_obj.kind == 'excellon':
  8018. alpha_level = str(hex(
  8019. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8020. elif sel_obj.kind == 'gerber':
  8021. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8022. elif sel_obj.kind == 'geometry':
  8023. alpha_level = 'FF'
  8024. else:
  8025. log.debug(
  8026. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8027. continue
  8028. sel_obj.alpha_level = alpha_level
  8029. if act_name == _('Red'):
  8030. new_color = '#FF0000' + alpha_level
  8031. if act_name == _('Blue'):
  8032. new_color = '#0000FF' + alpha_level
  8033. if act_name == _('Yellow'):
  8034. new_color = '#FFDF00' + alpha_level
  8035. if act_name == _('Green'):
  8036. new_color = '#00FF00' + alpha_level
  8037. if act_name == _('Purple'):
  8038. new_color = '#FF00FF' + alpha_level
  8039. if act_name == _('Brown'):
  8040. new_color = '#A52A2A' + alpha_level
  8041. if act_name == _('White'):
  8042. new_color = '#FFFFFF' + alpha_level
  8043. if act_name == _('Black'):
  8044. new_color = '#000000' + alpha_level
  8045. if act_name == _('Custom'):
  8046. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8047. c_dialog = QtWidgets.QColorDialog()
  8048. plot_fill_color = c_dialog.getColor(initial=new_color)
  8049. if plot_fill_color.isValid() is False:
  8050. return
  8051. new_color = str(plot_fill_color.name()) + alpha_level
  8052. if act_name == _("Default"):
  8053. for sel_obj in sel_obj_list:
  8054. if sel_obj.kind == 'excellon':
  8055. new_color = self.defaults['excellon_plot_fill']
  8056. new_line_color = self.defaults['excellon_plot_line']
  8057. elif sel_obj.kind == 'gerber':
  8058. new_color = self.defaults['gerber_plot_fill']
  8059. new_line_color = self.defaults['gerber_plot_line']
  8060. elif sel_obj.kind == 'geometry':
  8061. new_color = self.defaults['geometry_plot_line']
  8062. new_line_color = self.defaults['geometry_plot_line']
  8063. else:
  8064. log.debug(
  8065. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8066. continue
  8067. sel_obj.fill_color = new_color
  8068. sel_obj.outline_color = new_line_color
  8069. sel_obj.shapes.redraw(
  8070. update_colors=(new_color, new_line_color)
  8071. )
  8072. return
  8073. if act_name == _("Opacity"):
  8074. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8075. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8076. if ok_button:
  8077. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8078. for sel_obj in sel_obj_list:
  8079. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8080. sel_obj.shapes.redraw(
  8081. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8082. )
  8083. return
  8084. new_line_color = color_variant(new_color[:7], 0.7)
  8085. if act_name == _("White"):
  8086. new_line_color = color_variant("#dedede", 0.7)
  8087. for sel_obj in sel_obj_list:
  8088. sel_obj.fill_color = new_color
  8089. sel_obj.outline_color = new_line_color
  8090. sel_obj.shapes.redraw(
  8091. update_colors=(new_color, new_line_color)
  8092. )
  8093. def generate_cnc_job(self, objects):
  8094. """
  8095. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8096. :param objects: Selected objects in the Project Tab
  8097. :return:
  8098. """
  8099. self.defaults.report_usage("generate_cnc_job()")
  8100. # for obj in objects:
  8101. # obj.generatecncjob()
  8102. for obj in objects:
  8103. obj.on_generatecnc_button_click()
  8104. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8105. """
  8106. Saves the current project to the specified file.
  8107. :param filename: Name of the file in which to save.
  8108. :type filename: str
  8109. :param quit_action: if the project saving will be followed by an app quit; boolean
  8110. :param silent: if True will not display status messages
  8111. :param from_tcl True is run from Tcl Shell
  8112. :return: None
  8113. """
  8114. self.log.debug("save_project()")
  8115. self.save_in_progress = True
  8116. with self.proc_container.new(_("Saving FlatCAM Project")):
  8117. # Capture the latest changes
  8118. # Current object
  8119. try:
  8120. current_object = self.collection.get_active()
  8121. if current_object:
  8122. current_object.read_form()
  8123. except Exception as e:
  8124. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8125. pass
  8126. # Serialize the whole project
  8127. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8128. "options": self.options,
  8129. "version": self.version}
  8130. if self.defaults["global_save_compressed"] is True:
  8131. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8132. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8133. # # Write
  8134. f.write(g)
  8135. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8136. else:
  8137. # Open file
  8138. try:
  8139. f = open(filename, 'w')
  8140. except IOError:
  8141. App.log.error("Failed to open file for saving: %s", filename)
  8142. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8143. return
  8144. # Write
  8145. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8146. f.close()
  8147. # verification of the saved project
  8148. # Open and parse
  8149. try:
  8150. saved_f = open(filename, 'r')
  8151. except IOError:
  8152. if silent is False:
  8153. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8154. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8155. return
  8156. try:
  8157. saved_d = json.load(saved_f, object_hook=dict2obj)
  8158. except Exception:
  8159. if silent is False:
  8160. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8161. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8162. f.close()
  8163. return
  8164. saved_f.close()
  8165. if silent is False:
  8166. if 'version' in saved_d:
  8167. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8168. else:
  8169. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8170. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8171. tb_settings = QSettings("Open Source", "FlatCAM")
  8172. lock_state = self.ui.lock_action.isChecked()
  8173. tb_settings.setValue('toolbar_lock', lock_state)
  8174. # This will write the setting to the platform specific storage.
  8175. del tb_settings
  8176. # if quit:
  8177. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8178. # t.start()
  8179. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8180. def start_delayed_quit(self, delay, filename, should_quit=None):
  8181. """
  8182. :param delay: period of checking if project file size is more than zero; in seconds
  8183. :param filename: the name of the project file to be checked periodically for size more than zero
  8184. :param should_quit: if the task finished will be followed by an app quit; boolean
  8185. :return:
  8186. """
  8187. to_quit = should_quit
  8188. self.save_timer = QtCore.QTimer()
  8189. self.save_timer.setInterval(delay)
  8190. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8191. self.save_timer.start()
  8192. def check_project_file_size(self, filename, should_quit=None):
  8193. """
  8194. :param filename: the name of the project file to be checked periodically for size more than zero
  8195. :param should_quit: will quit the app if True; boolean
  8196. :return:
  8197. """
  8198. try:
  8199. if os.stat(filename).st_size > 0:
  8200. self.save_in_progress = False
  8201. self.save_timer.stop()
  8202. if should_quit:
  8203. self.app_quit.emit()
  8204. except Exception:
  8205. traceback.print_exc()
  8206. def save_project_auto(self):
  8207. """
  8208. Called periodically to save the project.
  8209. 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
  8210. # progress.
  8211. :return:
  8212. """
  8213. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8214. self.on_file_saveproject()
  8215. def save_project_auto_update(self):
  8216. """
  8217. Update the auto save time interval value.
  8218. :return:
  8219. """
  8220. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8221. try:
  8222. if self.autosave_timer.isActive():
  8223. self.autosave_timer.stop()
  8224. except Exception:
  8225. pass
  8226. if self.defaults['global_autosave'] is True:
  8227. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8228. self.autosave_timer.start()
  8229. def on_options_app2project(self):
  8230. """
  8231. Callback for Options->Transfer Options->App=>Project. Copies options
  8232. from application defaults to project defaults.
  8233. :return: None
  8234. """
  8235. self.defaults.report_usage("on_options_app2project")
  8236. self.preferencesUiManager.defaults_read_form()
  8237. self.options.update(self.defaults)
  8238. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8239. """
  8240. Shows a message on the FlatCAM Shell
  8241. :param msg: Message to display.
  8242. :param show: Opens the shell.
  8243. :param error: Shows the message as an error.
  8244. :param warning: Shows the message as an warning.
  8245. :param success: Shows the message as an success.
  8246. :param selected: Indicate that something was selected on canvas
  8247. :return: None
  8248. """
  8249. if show:
  8250. self.ui.shell_dock.show()
  8251. try:
  8252. if error:
  8253. self.shell.append_error(msg + "\n")
  8254. elif warning:
  8255. self.shell.append_warning(msg + "\n")
  8256. elif success:
  8257. self.shell.append_success(msg + "\n")
  8258. elif selected:
  8259. self.shell.append_selected(msg + "\n")
  8260. else:
  8261. self.shell.append_output(msg + "\n")
  8262. except AttributeError:
  8263. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8264. class ArgsThread(QtCore.QObject):
  8265. open_signal = pyqtSignal(list)
  8266. start = pyqtSignal()
  8267. stop = pyqtSignal()
  8268. if sys.platform == 'win32':
  8269. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8270. else:
  8271. address = ('/tmp/testipc', 'AF_UNIX')
  8272. def __init__(self):
  8273. super().__init__()
  8274. self.listener = None
  8275. self.thread_exit = False
  8276. self.start.connect(self.run)
  8277. self.stop.connect(self.close_listener)
  8278. def my_loop(self, address):
  8279. try:
  8280. self.listener = Listener(*address)
  8281. while self.thread_exit is False:
  8282. conn = self.listener.accept()
  8283. self.serve(conn)
  8284. except socket.error:
  8285. try:
  8286. conn = Client(*address)
  8287. conn.send(sys.argv)
  8288. conn.send('close')
  8289. # close the current instance only if there are args
  8290. if len(sys.argv) > 1:
  8291. try:
  8292. self.listener.close()
  8293. except Exception:
  8294. pass
  8295. sys.exit()
  8296. except ConnectionRefusedError:
  8297. if sys.platform == 'win32':
  8298. pass
  8299. else:
  8300. os.system('rm /tmp/testipc')
  8301. self.listener = Listener(*address)
  8302. while True:
  8303. conn = self.listener.accept()
  8304. self.serve(conn)
  8305. def serve(self, conn):
  8306. while self.thread_exit is False:
  8307. msg = conn.recv()
  8308. if msg == 'close':
  8309. break
  8310. self.open_signal.emit(msg)
  8311. conn.close()
  8312. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8313. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8314. @pyqtSlot()
  8315. def run(self):
  8316. self.my_loop(self.address)
  8317. @pyqtSlot()
  8318. def close_listener(self):
  8319. self.thread_exit = True
  8320. self.listener.close()
  8321. # end of file