App_Main.py 448 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010
  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 = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal(str)
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  699. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  700. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  701. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  702. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  703. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  704. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  705. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  706. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  707. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  708. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  709. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  710. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  711. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  712. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  713. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  714. # ToolBar signals
  715. self.connect_toolbar_signals()
  716. # Notebook and Plot Tab Area signals
  717. # make the right click on the notebook tab and plot tab area tab raise a menu
  718. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.on_tab_setup_context_menu()
  721. # activate initial state
  722. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  723. # Context Menu
  724. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  725. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  726. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  727. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  728. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  729. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  730. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  731. self.ui.clearplot.triggered.connect(self.clear_plots)
  732. self.ui.replot.triggered.connect(self.plot_all)
  733. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  734. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  735. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  736. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  737. self.ui.popmenu_move.triggered.connect(self.obj_move)
  738. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  739. # Project Context Menu -> Color Setting
  740. for act in self.ui.menuprojectcolor.actions():
  741. act.triggered.connect(self.on_set_color_action_triggered)
  742. # ###########################################################################################################
  743. # #################################### GUI PREFERENCES SIGNALS ##############################################
  744. # ###########################################################################################################
  745. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  746. lambda: self.on_toggle_units(no_pref=False))
  747. # ##################################### Workspace Setting Signals ###########################################
  748. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  749. self.on_workspace_modified)
  750. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  751. self.on_workspace_modified
  752. )
  753. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  754. # ###########################################################################################################
  755. # ######################################## GUI SETTINGS SIGNALS #############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  758. # ######################################## Tools related signals ############################################
  759. # portability changed signal
  760. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  761. # Object list
  762. self.object_status_changed.connect(self.collection.on_collection_updated)
  763. # when there are arguments at application startup this get launched
  764. self.args_at_startup[list].connect(self.on_startup_args)
  765. # ###########################################################################################################
  766. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  767. # ###########################################################################################################
  768. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  769. lambda: self.restore_extensions(ext_type='excellon'))
  770. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  771. lambda: self.restore_extensions(ext_type='gcode'))
  772. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  773. lambda: self.restore_extensions(ext_type='gerber'))
  774. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  775. lambda: self.delete_all_extensions(ext_type='excellon'))
  776. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  777. lambda: self.delete_all_extensions(ext_type='gcode'))
  778. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  779. lambda: self.delete_all_extensions(ext_type='gerber'))
  780. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  781. lambda: self.add_extension(ext_type='excellon'))
  782. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  783. lambda: self.add_extension(ext_type='gcode'))
  784. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  785. lambda: self.add_extension(ext_type='gerber'))
  786. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  787. lambda: self.del_extension(ext_type='excellon'))
  788. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  789. lambda: self.del_extension(ext_type='gcode'))
  790. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  791. lambda: self.del_extension(ext_type='gerber'))
  792. # connect the 'Apply' buttons from the Preferences/File Associations
  793. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  794. lambda: self.on_register_files(obj_type='excellon'))
  795. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  796. lambda: self.on_register_files(obj_type='gcode'))
  797. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  798. lambda: self.on_register_files(obj_type='gerber'))
  799. # ###########################################################################################################
  800. # ########################################### KEYWORDS SIGNALS ##############################################
  801. # ###########################################################################################################
  802. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  803. lambda: self.restore_extensions(ext_type='keyword'))
  804. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  805. lambda: self.delete_all_extensions(ext_type='keyword'))
  806. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='keyword'))
  808. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='keyword'))
  810. # connect the abort_all_tasks related slots to the related signals
  811. self.proc_container.idle_flag.connect(self.app_is_idle)
  812. # signal emitted when a tab is closed in the Plot Area
  813. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  814. # signal to close the application
  815. self.close_app_signal.connect(self.kill_app)
  816. # ################################# FINISHED CONNECTING SIGNALS #############################################
  817. # ###########################################################################################################
  818. # ###########################################################################################################
  819. # ###########################################################################################################
  820. self.log.debug("Finished connecting Signals.")
  821. # ###########################################################################################################
  822. # ########################################## Other setups ###################################################
  823. # ###########################################################################################################
  824. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  825. # depending on from where those tools are called different actions can be done
  826. self.call_source = 'app'
  827. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  828. self.tool_tab_locked = False
  829. # decide if to show or hide the Notebook side of the screen at startup
  830. if self.defaults["global_project_at_startup"] is True:
  831. self.ui.splitter.setSizes([1, 1])
  832. else:
  833. self.ui.splitter.setSizes([0, 1])
  834. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  835. self.setup_component_editor()
  836. # ###########################################################################################################
  837. # ####################################### Auto-complete KEYWORDS ############################################
  838. # ###########################################################################################################
  839. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  840. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  841. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  842. 'export_exc',
  843. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  844. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  845. 'interiors', 'isolate', 'join_excellon',
  846. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  847. 'mirror', 'ncc',
  848. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  849. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  850. 'options', 'origin',
  851. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  852. 'save', 'save_project',
  853. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  854. 'skew', 'subtract_poly', 'subtract_rectangle',
  855. 'version', 'write_gcode'
  856. ]
  857. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  858. 'Paste_1',
  859. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  860. 'Toolchange_manual', 'True', 'Users',
  861. 'all', 'auto', 'axis',
  862. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  863. 'contour', 'default',
  864. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  865. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  866. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  867. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  868. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  869. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  870. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  871. 'spacing_columns',
  872. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  873. 'toolchange_xy', 'toolchangez', 'travelz',
  874. 'tooldia', 'use_threads', 'value',
  875. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  876. ]
  877. self.tcl_keywords = [
  878. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  879. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  880. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  881. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  882. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  883. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  884. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  885. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  886. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  887. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  888. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  889. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  890. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  891. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  892. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  893. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  894. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  895. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  896. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  897. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  898. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  899. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  900. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  901. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  902. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  903. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  904. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  905. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  906. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  907. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  908. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  909. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  910. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  911. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  912. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  913. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  914. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  915. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  916. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  917. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  918. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  919. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  920. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  921. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  922. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  923. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  924. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  925. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  926. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  927. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  928. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  929. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  930. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  931. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  932. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  933. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  934. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  935. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  936. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  937. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  938. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  939. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  940. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  941. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  942. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  943. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  944. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  945. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  946. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  947. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  948. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  949. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  950. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  951. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  952. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  953. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  954. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  955. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  956. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  957. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  958. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  959. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  960. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  961. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  962. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  963. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  964. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  965. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  966. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  967. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  968. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  969. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  970. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  971. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  972. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  973. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  974. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  975. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  976. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  977. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  978. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  979. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  980. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  981. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  982. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  983. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  984. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  985. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  986. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  987. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  988. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  989. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  990. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  991. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  992. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  993. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  994. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  995. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  996. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  997. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  998. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  999. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1000. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1001. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1002. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1003. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1004. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1005. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1006. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1007. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1008. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1009. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1010. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1011. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1012. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1013. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1014. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1015. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1016. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1017. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1018. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1019. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1020. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1021. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1022. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1023. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1024. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1025. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1026. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1027. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1028. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1029. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1030. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1031. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1032. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1033. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1034. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1035. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1036. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1037. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1038. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1039. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1040. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1041. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1042. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1043. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1044. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1045. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1046. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1047. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1048. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1049. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1050. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1051. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1052. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1053. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1054. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1055. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1056. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1057. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1058. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1059. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1060. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1061. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1062. ]
  1063. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1064. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1065. # ###########################################################################################################
  1066. # ############################################## Shell SETUP ################################################
  1067. # ###########################################################################################################
  1068. self.shell = FCShell(app=self, version=self.version)
  1069. self.ui.shell_dock.setWidget(self.shell)
  1070. self.log.debug("TCL Shell has been initialized.")
  1071. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1072. if self.defaults["global_shell_at_startup"]:
  1073. self.ui.shell_dock.show()
  1074. else:
  1075. self.ui.shell_dock.hide()
  1076. # ###########################################################################################################
  1077. # ########################################## Tools and Plugins ##############################################
  1078. # ###########################################################################################################
  1079. self.dblsidedtool = None
  1080. self.distance_tool = None
  1081. self.distance_min_tool = None
  1082. self.panelize_tool = None
  1083. self.film_tool = None
  1084. self.paste_tool = None
  1085. self.calculator_tool = None
  1086. self.rules_tool = None
  1087. self.sub_tool = None
  1088. self.move_tool = None
  1089. self.cutout_tool = None
  1090. self.ncclear_tool = None
  1091. self.paint_tool = None
  1092. self.isolation_tool = None
  1093. self.optimal_tool = None
  1094. self.transform_tool = None
  1095. self.properties_tool = None
  1096. self.pdf_tool = None
  1097. self.image_tool = None
  1098. self.pcb_wizard_tool = None
  1099. self.cal_exc_tool = None
  1100. self.qrcode_tool = None
  1101. self.copper_thieving_tool = None
  1102. self.fiducial_tool = None
  1103. self.edrills_tool = None
  1104. self.align_objects_tool = None
  1105. self.punch_tool = None
  1106. self.invert_tool = None
  1107. self.corners_tool = None
  1108. self.etch_tool = None
  1109. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1110. try:
  1111. self.install_tools()
  1112. except AttributeError as e:
  1113. log.debug("App.__init__() install tools() --> %s" % str(e))
  1114. # ###########################################################################################################
  1115. # ############################################ SETUP RECENT ITEMS ###########################################
  1116. # ###########################################################################################################
  1117. self.setup_recent_items()
  1118. # ###########################################################################################################
  1119. # ######################################### BookMarks Manager ###############################################
  1120. # ###########################################################################################################
  1121. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1122. self.install_bookmarks()
  1123. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1124. # ###########################################################################################################
  1125. # ########################################### Tools Database ################################################
  1126. # ###########################################################################################################
  1127. self.tools_db_tab = None
  1128. # ### System Font Parsing ###
  1129. # self.f_parse = ParseFont(self)
  1130. # self.parse_system_fonts()
  1131. # ###########################################################################################################
  1132. # ######################################### Check for updates ###############################################
  1133. # ###########################################################################################################
  1134. # Separate thread (Not worker)
  1135. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1136. if (self.beta is False or self.beta is None) and \
  1137. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1138. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1139. # self.thr2 = QtCore.QThread()
  1140. self.worker_task.emit({'fcn': self.version_check,
  1141. 'params': []})
  1142. # self.thr2.start(QtCore.QThread.LowPriority)
  1143. # ###########################################################################################################
  1144. # ##################################### Register files with FlatCAM; #######################################
  1145. # ################################### It works only for Windows for now ####################################
  1146. # ###########################################################################################################
  1147. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1148. self.on_register_files()
  1149. # ###########################################################################################################
  1150. # ######################################## Variables for global usage #######################################
  1151. # ###########################################################################################################
  1152. # hold the App units
  1153. self.units = 'MM'
  1154. # coordinates for relative position display
  1155. self.rel_point1 = (0, 0)
  1156. self.rel_point2 = (0, 0)
  1157. # variable to store coordinates
  1158. self.pos = (0, 0)
  1159. self.pos_canvas = (0, 0)
  1160. self.pos_jump = (0, 0)
  1161. # variable to store mouse coordinates
  1162. self.mouse = [0, 0]
  1163. # variable to store the delta positions on cavnas
  1164. self.dx = 0
  1165. self.dy = 0
  1166. # decide if we have a double click or single click
  1167. self.doubleclick = False
  1168. # store here the is_dragging value
  1169. self.event_is_dragging = False
  1170. # variable to store if a command is active (then the var is not None) and which one it is
  1171. self.command_active = None
  1172. # variable to store the status of moving selection action
  1173. # None value means that it's not an selection action
  1174. # True value = a selection from left to right
  1175. # False value = a selection from right to left
  1176. self.selection_type = None
  1177. # List to store the objects that are currently loaded in FlatCAM
  1178. # This list is updated on each object creation or object delete
  1179. self.all_objects_list = []
  1180. self.objects_under_the_click_list = []
  1181. # List to store the objects that are selected
  1182. self.sel_objects_list = []
  1183. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1184. self.key_modifiers = None
  1185. # Variable to hold the status of the axis
  1186. self.toggle_axis = True
  1187. # Variable to hold the status of the grid lines
  1188. self.toggle_grid_lines = True
  1189. # Variable to store the status of the code editor
  1190. self.toggle_codeeditor = False
  1191. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1192. self.click_noproject = False
  1193. self.cursor = None
  1194. # Variable to store the GCODE that was edited
  1195. self.gcode_edited = ""
  1196. self.text_editor_tab = None
  1197. # reference for the self.ui.code_editor
  1198. self.reference_code_editor = None
  1199. self.script_code = ''
  1200. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1201. self.tools_db_changed_flag = False
  1202. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1203. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1204. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1205. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1206. 'tsm']
  1207. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1208. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1209. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1210. 'sbp', 'tap', 'xpi']
  1211. self.svg_list = ['svg']
  1212. self.dxf_list = ['dxf']
  1213. self.pdf_list = ['pdf']
  1214. self.prj_list = ['flatprj']
  1215. self.conf_list = ['flatconfig']
  1216. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1217. # flag for polygons not cleared
  1218. self.poly_not_cleared = False
  1219. # VisPy visuals
  1220. self.isHovering = False
  1221. self.notHovering = True
  1222. # Window geometry
  1223. self.x_pos = None
  1224. self.y_pos = None
  1225. self.width = None
  1226. self.height = None
  1227. # when True, the app has to return from any thread
  1228. self.abort_flag = False
  1229. # set the value used in the Windows Title
  1230. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1231. # this holds a widget that is installed in the Plot Area when View Source option is used
  1232. self.source_editor_tab = None
  1233. self.pagesize = {}
  1234. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1235. # VisPy visuals
  1236. if self.is_legacy is False:
  1237. try:
  1238. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1239. except AttributeError:
  1240. self.tool_shapes = None
  1241. else:
  1242. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1243. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1244. # used in the delayed shutdown self.start_delayed_quit() method
  1245. self.save_timer = None
  1246. # ###########################################################################################################
  1247. # ################################## ADDING FlatCAM EDITORS section #########################################
  1248. # ###########################################################################################################
  1249. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1250. # at the first launch of the App , the editors will not be functional.
  1251. try:
  1252. self.geo_editor = FlatCAMGeoEditor(self)
  1253. except AttributeError:
  1254. pass
  1255. try:
  1256. self.exc_editor = FlatCAMExcEditor(self)
  1257. except AttributeError:
  1258. pass
  1259. try:
  1260. self.grb_editor = FlatCAMGrbEditor(self)
  1261. except AttributeError:
  1262. pass
  1263. self.log.debug("Finished adding FlatCAM Editor's.")
  1264. self.set_ui_title(name=_("New Project - Not saved"))
  1265. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1266. current_platform = platform.architecture()[0]
  1267. if current_platform != '64bit':
  1268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1270. # ###########################################################################################################
  1271. # ########################################### EXCLUSION AREAS ###############################################
  1272. # ###########################################################################################################
  1273. self.exc_areas = ExclusionAreas(app=self)
  1274. # ###########################################################################################################
  1275. # ##################################### Finished the CONSTRUCTOR ############################################
  1276. # ###########################################################################################################
  1277. App.log.debug("END of constructor. Releasing control.")
  1278. # ###########################################################################################################
  1279. # ########################################## SHOW GUI #######################################################
  1280. # ###########################################################################################################
  1281. # if the app is not started as headless, show it
  1282. if self.cmd_line_headless != 1:
  1283. if show_splash:
  1284. # finish the splash
  1285. self.splash.finish(self.ui)
  1286. mgui_settings = QSettings("Open Source", "FlatCAM")
  1287. if mgui_settings.contains("maximized_gui"):
  1288. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1289. if maximized_ui is True:
  1290. self.ui.showMaximized()
  1291. else:
  1292. self.ui.show()
  1293. else:
  1294. self.ui.show()
  1295. if self.defaults["global_systray_icon"]:
  1296. self.trayIcon.show()
  1297. else:
  1298. log.warning("******************* RUNNING HEADLESS *******************")
  1299. # ###########################################################################################################
  1300. # ######################################## START-UP ARGUMENTS ###############################################
  1301. # ###########################################################################################################
  1302. # test if the program was started with a script as parameter
  1303. if self.cmd_line_shellvar:
  1304. try:
  1305. cnt = 0
  1306. command_tcl = 0
  1307. for i in self.cmd_line_shellvar.split(','):
  1308. if i is not None:
  1309. # noinspection PyBroadException
  1310. try:
  1311. command_tcl = eval(i)
  1312. except Exception:
  1313. command_tcl = i
  1314. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1315. cnt += 1
  1316. # if there are Windows paths then replace the path separator with a Unix like one
  1317. if sys.platform == 'win32':
  1318. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1319. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1320. except Exception as ext:
  1321. print("ERROR: ", ext)
  1322. sys.exit(2)
  1323. if self.cmd_line_shellfile:
  1324. if self.cmd_line_headless != 1:
  1325. if self.ui.shell_dock.isHidden():
  1326. self.ui.shell_dock.show()
  1327. try:
  1328. with open(self.cmd_line_shellfile, "r") as myfile:
  1329. # if show_splash:
  1330. # self.splash.showMessage('%s: %ssec\n%s' % (
  1331. # _("Canvas initialization started.\n"
  1332. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1333. # _("Executing Tcl Script ...")),
  1334. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1335. # color=QtGui.QColor("gray"))
  1336. cmd_line_shellfile_text = myfile.read()
  1337. if self.cmd_line_headless != 1:
  1338. self.shell.exec_command(cmd_line_shellfile_text)
  1339. else:
  1340. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1341. except Exception as ext:
  1342. print("ERROR: ", ext)
  1343. sys.exit(2)
  1344. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1345. # the path/file_name must be enclosed in quotes if it contain spaces
  1346. if App.args:
  1347. self.args_at_startup.emit(App.args)
  1348. if self.defaults.old_defaults_found is True:
  1349. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1350. "Please reboot the application to update."))
  1351. self.defaults.old_defaults_found = False
  1352. # ######################################### INIT FINISHED #######################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. # #################################################################################################################
  1358. @staticmethod
  1359. def copy_and_overwrite(from_path, to_path):
  1360. """
  1361. From here:
  1362. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1363. :param from_path: source path
  1364. :param to_path: destination path
  1365. :return: None
  1366. """
  1367. if os.path.exists(to_path):
  1368. shutil.rmtree(to_path)
  1369. try:
  1370. shutil.copytree(from_path, to_path)
  1371. except FileNotFoundError:
  1372. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1373. shutil.copytree(from_new_path, to_path)
  1374. def on_startup_args(self, args, silent=False):
  1375. """
  1376. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1377. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1378. :param args: a list containing the application args at startup
  1379. :return: None
  1380. """
  1381. if args is not None:
  1382. args_to_process = args
  1383. else:
  1384. args_to_process = App.args
  1385. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1386. for argument in args_to_process:
  1387. if '.FlatPrj'.lower() in argument.lower():
  1388. try:
  1389. project_name = str(argument)
  1390. if project_name == "":
  1391. if silent is False:
  1392. self.inform.emit(_("Cancelled."))
  1393. else:
  1394. # self.open_project(project_name)
  1395. run_from_arg = True
  1396. # self.worker_task.emit({'fcn': self.open_project,
  1397. # 'params': [project_name, run_from_arg]})
  1398. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1399. except Exception as e:
  1400. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1401. elif '.FlatConfig'.lower() in argument.lower():
  1402. try:
  1403. file_name = str(argument)
  1404. if file_name == "":
  1405. if silent is False:
  1406. self.inform.emit(_("Open Config file failed."))
  1407. else:
  1408. run_from_arg = True
  1409. # self.worker_task.emit({'fcn': self.open_config_file,
  1410. # 'params': [file_name, run_from_arg]})
  1411. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1412. except Exception as e:
  1413. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1414. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1415. try:
  1416. file_name = str(argument)
  1417. if file_name == "":
  1418. if silent is False:
  1419. self.inform.emit(_("Open Script file failed."))
  1420. else:
  1421. if silent is False:
  1422. self.on_fileopenscript(name=file_name)
  1423. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1424. self.on_filerunscript(name=file_name)
  1425. except Exception as e:
  1426. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1427. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1428. log.debug("App.on_startup_args() --> Quit event.")
  1429. sys.exit()
  1430. elif 'save'.lower() in argument.lower():
  1431. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1432. self.preferencesUiManager.save_defaults()
  1433. else:
  1434. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1435. proc_arg = argument.lower()
  1436. for ext in exc_list:
  1437. proc_ext = ext.replace(' ', '')
  1438. proc_ext = '.%s' % proc_ext
  1439. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Excellon file failed."))
  1444. else:
  1445. self.on_fileopenexcellon(name=file_name, signal=None)
  1446. return
  1447. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1448. for ext in gco_list:
  1449. proc_ext = ext.replace(' ', '')
  1450. proc_ext = '.%s' % proc_ext
  1451. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open GCode file failed."))
  1456. else:
  1457. self.on_fileopengcode(name=file_name, signal=None)
  1458. return
  1459. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1460. for ext in grb_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 Gerber file failed."))
  1468. else:
  1469. self.on_fileopengerber(name=file_name, signal=None)
  1470. return
  1471. # if it reached here without already returning then the app was registered with a file that it does not
  1472. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1473. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1474. # for arg in args_to_process:
  1475. # if 'FlatCAM.exe' in arg:
  1476. # continue
  1477. # else:
  1478. # sys.exit(2)
  1479. def set_ui_title(self, name):
  1480. """
  1481. Sets the title of the main window.
  1482. :param name: String that store the project path and project name
  1483. :return: None
  1484. """
  1485. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1486. (self.version,
  1487. ('BETA' if self.beta else ''),
  1488. platform.architecture()[0],
  1489. self.engine,
  1490. name)
  1491. )
  1492. def on_app_restart(self):
  1493. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1494. # be left in the SySTray
  1495. try:
  1496. self.trayIcon.hide()
  1497. except Exception:
  1498. pass
  1499. fcTranslate.restart_program(app=self)
  1500. def clear_pool(self):
  1501. """
  1502. Clear the multiprocessing pool and calls garbage collector.
  1503. :return: None
  1504. """
  1505. self.pool.close()
  1506. self.pool = Pool()
  1507. self.pool_recreated.emit(self.pool)
  1508. gc.collect()
  1509. def install_tools(self):
  1510. """
  1511. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1512. Instantiation of the Tools classes.
  1513. The order that the tools are installed is important as they can depend on each other install position.
  1514. :return: None
  1515. """
  1516. self.distance_tool = Distance(self)
  1517. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1518. before=self.ui.menueditorigin,
  1519. separator=False)
  1520. self.distance_min_tool = DistanceMin(self)
  1521. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1522. pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=True)
  1525. self.dblsidedtool = DblSidedTool(self)
  1526. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1527. self.cal_exc_tool = ToolCalibration(self)
  1528. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1529. before=self.dblsidedtool.menuAction,
  1530. separator=False)
  1531. self.align_objects_tool = AlignObjects(self)
  1532. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1533. self.edrills_tool = ToolExtractDrills(self)
  1534. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1535. self.panelize_tool = Panelize(self)
  1536. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1537. self.film_tool = Film(self)
  1538. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1539. self.paste_tool = SolderPaste(self)
  1540. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1541. self.calculator_tool = ToolCalculator(self)
  1542. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1543. self.sub_tool = ToolSub(self)
  1544. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1545. pos=self.ui.menutool, separator=True)
  1546. self.rules_tool = RulesCheck(self)
  1547. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1548. pos=self.ui.menutool, separator=False)
  1549. self.optimal_tool = ToolOptimal(self)
  1550. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1551. pos=self.ui.menutool, separator=True)
  1552. self.move_tool = ToolMove(self)
  1553. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin, separator=True)
  1555. self.cutout_tool = CutOut(self)
  1556. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1557. before=self.sub_tool.menuAction)
  1558. self.ncclear_tool = NonCopperClear(self)
  1559. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1560. before=self.sub_tool.menuAction, separator=True)
  1561. self.paint_tool = ToolPaint(self)
  1562. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1563. before=self.sub_tool.menuAction, separator=True)
  1564. self.isolation_tool = ToolIsolation(self)
  1565. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1566. before=self.sub_tool.menuAction, separator=True)
  1567. self.copper_thieving_tool = ToolCopperThieving(self)
  1568. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1569. pos=self.ui.menutool)
  1570. self.fiducial_tool = ToolFiducials(self)
  1571. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1572. pos=self.ui.menutool)
  1573. self.qrcode_tool = QRCode(self)
  1574. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1575. pos=self.ui.menutool)
  1576. self.punch_tool = ToolPunchGerber(self)
  1577. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1578. self.invert_tool = ToolInvertGerber(self)
  1579. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1580. self.corners_tool = ToolCorners(self)
  1581. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1582. self.etch_tool = ToolEtchCompensation(self)
  1583. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1584. self.transform_tool = ToolTransform(self)
  1585. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1586. pos=self.ui.menuoptions, separator=True)
  1587. self.properties_tool = Properties(self)
  1588. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1589. pos=self.ui.menuoptions)
  1590. self.pdf_tool = ToolPDF(self)
  1591. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1592. pos=self.ui.menufileimport,
  1593. separator=True)
  1594. self.image_tool = ToolImage(self)
  1595. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1596. pos=self.ui.menufileimport,
  1597. separator=True)
  1598. self.pcb_wizard_tool = PcbWizard(self)
  1599. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1600. pos=self.ui.menufileimport)
  1601. self.log.debug("Tools are installed.")
  1602. def remove_tools(self):
  1603. """
  1604. Will remove all the actions in the Tool menu.
  1605. :return: None
  1606. """
  1607. for act in self.ui.menutool.actions():
  1608. self.ui.menutool.removeAction(act)
  1609. def init_tools(self):
  1610. """
  1611. Initialize the Tool tab in the notebook side of the central widget.
  1612. Remove the actions in the Tools menu.
  1613. Instantiate again the FlatCAM tools (plugins).
  1614. All this is required when changing the layout: standard, compact etc.
  1615. :return: None
  1616. """
  1617. log.debug("init_tools()")
  1618. # delete the data currently in the Tools Tab and the Tab itself
  1619. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1620. if widget is not None:
  1621. widget.deleteLater()
  1622. self.ui.notebook.removeTab(2)
  1623. # rebuild the Tools Tab
  1624. self.ui.tool_tab = QtWidgets.QWidget()
  1625. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1626. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1627. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1628. self.ui.tool_scroll_area = VerticalScrollArea()
  1629. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1630. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1631. # first remove all of them
  1632. self.remove_tools()
  1633. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1634. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1635. '&Command Line\tS')
  1636. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1637. # third install all of them
  1638. try:
  1639. self.install_tools()
  1640. except AttributeError:
  1641. pass
  1642. self.log.debug("Tools are initialized.")
  1643. # def parse_system_fonts(self):
  1644. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1645. # 'params': []})
  1646. def connect_toolbar_signals(self):
  1647. """
  1648. Reconnect the signals to the actions in the toolbar.
  1649. This has to be done each time after the FlatCAM tools are removed/installed.
  1650. :return: None
  1651. """
  1652. # Toolbar
  1653. # File Toolbar Signals
  1654. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1655. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1656. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1657. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1658. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1659. # View Toolbar Signals
  1660. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1661. self.ui.replot_btn.triggered.connect(self.plot_all)
  1662. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1663. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1664. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1665. # Edit Toolbar Signals
  1666. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1667. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1668. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1669. self.ui.delete_btn.triggered.connect(self.on_delete)
  1670. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1671. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1672. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1673. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1674. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1675. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1676. # Scripting Toolbar Signals
  1677. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1678. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1679. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1680. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1681. # Tools Toolbar Signals
  1682. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1683. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1684. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1685. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1686. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1687. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1688. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1689. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1690. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1691. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1692. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1693. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1694. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1695. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1696. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1697. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1698. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1699. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1700. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1701. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1702. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1703. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1704. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1705. def object2editor(self):
  1706. """
  1707. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1708. :return: None
  1709. """
  1710. self.defaults.report_usage("object2editor()")
  1711. # disable the objects menu as it may interfere with the AppEditors
  1712. self.ui.menuobjects.setDisabled(True)
  1713. edited_object = self.collection.get_active()
  1714. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1715. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1716. pass
  1717. else:
  1718. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1719. return
  1720. if isinstance(edited_object, GeometryObject):
  1721. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1722. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1723. # we set the notebook to hidden
  1724. # self.ui.splitter.setSizes([0, 1])
  1725. if edited_object.multigeo is True:
  1726. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1727. if len(sel_rows) > 1:
  1728. self.inform.emit('[WARNING_NOTCL] %s' %
  1729. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1730. "is not possible.\n"
  1731. "Edit only one geometry at a time."))
  1732. # determine the tool dia of the selected tool
  1733. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1734. # now find the key in the edited_object.tools that has this tooldia
  1735. multi_tool = 1
  1736. for tool in edited_object.tools:
  1737. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1738. multi_tool = tool
  1739. break
  1740. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1741. else:
  1742. self.geo_editor.edit_fcgeometry(edited_object)
  1743. # set call source to the Editor we go into
  1744. self.call_source = 'geo_editor'
  1745. elif isinstance(edited_object, ExcellonObject):
  1746. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1747. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1748. if self.ui.splitter.sizes()[0] == 0:
  1749. self.ui.splitter.setSizes([1, 1])
  1750. self.exc_editor.edit_fcexcellon(edited_object)
  1751. # set call source to the Editor we go into
  1752. self.call_source = 'exc_editor'
  1753. elif isinstance(edited_object, GerberObject):
  1754. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1755. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1756. if self.ui.splitter.sizes()[0] == 0:
  1757. self.ui.splitter.setSizes([1, 1])
  1758. self.grb_editor.edit_fcgerber(edited_object)
  1759. # set call source to the Editor we go into
  1760. self.call_source = 'grb_editor'
  1761. # reset the following variables so the UI is built again after edit
  1762. edited_object.ui_build = False
  1763. edited_object.build_aperture_storage = False
  1764. elif isinstance(edited_object, CNCJobObject):
  1765. if self.ui.splitter.sizes()[0] == 0:
  1766. self.ui.splitter.setSizes([1, 1])
  1767. edited_object.on_edit_code_click()
  1768. return
  1769. # make sure that we can't select another object while in Editor Mode:
  1770. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1771. self.ui.project_frame.setDisabled(True)
  1772. # delete any selection shape that might be active as they are not relevant in Editor
  1773. self.delete_selection_shape()
  1774. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1775. self.ui.plot_tab_area.protectTab(0)
  1776. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1777. self.should_we_save = True
  1778. def editor2object(self, cleanup=None):
  1779. """
  1780. Transfers the Geometry or Excellon from it's editor to the current object.
  1781. :return: None
  1782. """
  1783. self.defaults.report_usage("editor2object()")
  1784. # re-enable the objects menu that was disabled on entry in Editor mode
  1785. self.ui.menuobjects.setDisabled(False)
  1786. # do not update a geometry or excellon object unless it comes out of an editor
  1787. if self.call_source != 'app':
  1788. edited_obj = self.collection.get_active()
  1789. if cleanup is None:
  1790. msgbox = QtWidgets.QMessageBox()
  1791. msgbox.setText(_("Do you want to save the edited object?"))
  1792. msgbox.setWindowTitle(_("Close Editor"))
  1793. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1794. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1795. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1796. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1797. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1798. msgbox.setDefaultButton(bt_yes)
  1799. msgbox.exec_()
  1800. response = msgbox.clickedButton()
  1801. if response == bt_yes:
  1802. # clean the Tools Tab
  1803. self.ui.tool_scroll_area.takeWidget()
  1804. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1805. self.ui.notebook.setTabText(2, "Tool")
  1806. if isinstance(edited_obj, GeometryObject):
  1807. obj_type = "Geometry"
  1808. self.geo_editor.update_fcgeometry(edited_obj)
  1809. # self.geo_editor.update_options(edited_obj)
  1810. # restore GUI to the Selected TAB
  1811. # Remove anything else in the AppGUI
  1812. self.ui.tool_scroll_area.takeWidget()
  1813. # update the geo object options so it is including the bounding box values
  1814. try:
  1815. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1816. edited_obj.options['xmin'] = xmin
  1817. edited_obj.options['ymin'] = ymin
  1818. edited_obj.options['xmax'] = xmax
  1819. edited_obj.options['ymax'] = ymax
  1820. except AttributeError as e:
  1821. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1822. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1823. edited_obj.build_ui()
  1824. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1825. elif isinstance(edited_obj, GerberObject):
  1826. obj_type = "Gerber"
  1827. self.grb_editor.update_fcgerber()
  1828. # self.grb_editor.update_options(edited_obj)
  1829. # delete the old object (the source object) if it was an empty one
  1830. try:
  1831. if len(edited_obj.solid_geometry) == 0:
  1832. old_name = edited_obj.options['name']
  1833. self.collection.delete_by_name(old_name)
  1834. except TypeError:
  1835. # if the solid_geometry is a single Polygon the len() will not work
  1836. # in any case, falling here means that we have something in the solid_geometry, even if only
  1837. # a single Polygon, therefore we pass this
  1838. pass
  1839. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1840. # restore GUI to the Selected TAB
  1841. # Remove anything else in the AppGUI
  1842. self.ui.selected_scroll_area.takeWidget()
  1843. elif isinstance(edited_obj, ExcellonObject):
  1844. obj_type = "Excellon"
  1845. self.exc_editor.update_fcexcellon(edited_obj)
  1846. # self.exc_editor.update_options(edited_obj)
  1847. # restore GUI to the Selected TAB
  1848. # Remove anything else in the AppGUI
  1849. self.ui.tool_scroll_area.takeWidget()
  1850. # delete the old object (the source object) if it was an empty one
  1851. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.delete_by_name(name=old_name)
  1854. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1855. else:
  1856. self.inform.emit('[WARNING_NOTCL] %s' %
  1857. _("Select a Gerber, Geometry or Excellon Object to update."))
  1858. return
  1859. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1860. elif response == bt_no:
  1861. # clean the Tools Tab
  1862. self.ui.tool_scroll_area.takeWidget()
  1863. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1864. self.ui.notebook.setTabText(2, "Tool")
  1865. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1866. if isinstance(edited_obj, GeometryObject):
  1867. self.geo_editor.deactivate()
  1868. edited_obj.build_ui()
  1869. elif isinstance(edited_obj, GerberObject):
  1870. self.grb_editor.deactivate_grb_editor()
  1871. edited_obj.build_ui()
  1872. elif isinstance(edited_obj, ExcellonObject):
  1873. self.exc_editor.deactivate()
  1874. edited_obj.build_ui()
  1875. else:
  1876. self.inform.emit('[WARNING_NOTCL] %s' %
  1877. _("Select a Gerber, Geometry or Excellon Object to update."))
  1878. return
  1879. elif response == bt_cancel:
  1880. return
  1881. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1882. # edited_obj.build_ui()
  1883. # Switch notebook to Selected page
  1884. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1885. else:
  1886. if isinstance(edited_obj, GeometryObject):
  1887. self.geo_editor.deactivate()
  1888. elif isinstance(edited_obj, GerberObject):
  1889. self.grb_editor.deactivate_grb_editor()
  1890. elif isinstance(edited_obj, ExcellonObject):
  1891. self.exc_editor.deactivate()
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. # if notebook is hidden we show it
  1897. if self.ui.splitter.sizes()[0] == 0:
  1898. self.ui.splitter.setSizes([1, 1])
  1899. # restore the call_source to app
  1900. self.call_source = 'app'
  1901. # edited_obj.plot()
  1902. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1903. self.ui.plot_tab_area.protectTab(0)
  1904. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1905. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1906. self.ui.project_frame.setDisabled(False)
  1907. def get_last_folder(self):
  1908. """
  1909. Get the folder path from where the last file was opened.
  1910. :return: String, last opened folder path
  1911. """
  1912. return self.defaults["global_last_folder"]
  1913. def get_last_save_folder(self):
  1914. """
  1915. Get the folder path from where the last file was saved.
  1916. :return: String, last saved folder path
  1917. """
  1918. loc = self.defaults["global_last_save_folder"]
  1919. if loc is None:
  1920. loc = self.defaults["global_last_folder"]
  1921. if loc is None:
  1922. loc = os.path.dirname(__file__)
  1923. return loc
  1924. def info(self, msg):
  1925. """
  1926. Informs the user. Normally on the status bar, optionally
  1927. also on the shell.
  1928. :param msg: Text to write.
  1929. :return: None
  1930. """
  1931. # Type of message in brackets at the beginning of the message.
  1932. match = re.search(r"\[(.*)\](.*)", msg)
  1933. if match:
  1934. level = match.group(1)
  1935. msg_ = match.group(2)
  1936. self.ui.fcinfo.set_status(str(msg_), level=level)
  1937. if level.lower() == "error":
  1938. self.shell_message(msg, error=True, show=True)
  1939. elif level.lower() == "warning":
  1940. self.shell_message(msg, warning=True, show=True)
  1941. elif level.lower() == "error_notcl":
  1942. self.shell_message(msg, error=True, show=False)
  1943. elif level.lower() == "warning_notcl":
  1944. self.shell_message(msg, warning=True, show=False)
  1945. elif level.lower() == "success":
  1946. self.shell_message(msg, success=True, show=False)
  1947. elif level.lower() == "selected":
  1948. self.shell_message(msg, selected=True, show=False)
  1949. else:
  1950. self.shell_message(msg, show=False)
  1951. else:
  1952. self.ui.fcinfo.set_status(str(msg), level="info")
  1953. # make sure that if the message is to clear the infobar with a space
  1954. # is not printed over and over on the shell
  1955. if msg != '':
  1956. self.shell_message(msg)
  1957. def on_import_preferences(self):
  1958. """
  1959. Loads the application default settings from a saved file into
  1960. ``self.defaults`` dictionary.
  1961. :return: None
  1962. """
  1963. self.defaults.report_usage("on_import_preferences")
  1964. App.log.debug("App.on_import_preferences()")
  1965. # Show file chooser
  1966. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1967. try:
  1968. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1969. directory=self.data_path,
  1970. filter=filter_)
  1971. except TypeError:
  1972. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1973. filter=filter_)
  1974. filename = str(filename)
  1975. if filename == "":
  1976. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1977. return
  1978. # Load in the defaults from the chosen file
  1979. self.defaults.load(filename=filename)
  1980. self.preferencesUiManager.on_preferences_edited()
  1981. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1982. def on_export_preferences(self):
  1983. """
  1984. Save the defaults dictionary to a file.
  1985. :return: None
  1986. """
  1987. self.defaults.report_usage("on_export_preferences")
  1988. App.log.debug("on_export_preferences()")
  1989. # defaults_file_content = None
  1990. # Show file chooser
  1991. date = str(datetime.today()).rpartition('.')[0]
  1992. date = ''.join(c for c in date if c not in ':-')
  1993. date = date.replace(' ', '_')
  1994. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1995. try:
  1996. filename, _f = FCFileSaveDialog.get_saved_filename(
  1997. caption=_("Export FlatCAM Preferences"),
  1998. directory=self.data_path + '/preferences_' + date,
  1999. filter=filter__
  2000. )
  2001. except TypeError:
  2002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2003. filename = str(filename)
  2004. if filename == "":
  2005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2006. return
  2007. # Update options
  2008. self.preferencesUiManager.defaults_read_form()
  2009. self.defaults.propagate_defaults()
  2010. # Save update options
  2011. try:
  2012. self.defaults.write(filename=filename)
  2013. except Exception:
  2014. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2015. return
  2016. if self.defaults["global_open_style"] is False:
  2017. self.file_opened.emit("preferences", filename)
  2018. self.file_saved.emit("preferences", filename)
  2019. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2020. def save_to_file(self, content_to_save, txt_content):
  2021. """
  2022. Save something to a file.
  2023. :return: None
  2024. """
  2025. self.defaults.report_usage("save_to_file")
  2026. App.log.debug("save_to_file()")
  2027. self.date = str(datetime.today()).rpartition('.')[0]
  2028. self.date = ''.join(c for c in self.date if c not in ':-')
  2029. self.date = self.date.replace(' ', '_')
  2030. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2031. path_to_save = self.defaults["global_last_save_folder"] if \
  2032. self.defaults["global_last_save_folder"] is not None else self.data_path
  2033. try:
  2034. filename, _f = FCFileSaveDialog.get_saved_filename(
  2035. caption=_("Save to file"),
  2036. directory=path_to_save + '/file_' + self.date,
  2037. filter=filter__
  2038. )
  2039. except TypeError:
  2040. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2041. filename = str(filename)
  2042. if filename == "":
  2043. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2044. return
  2045. else:
  2046. try:
  2047. with open(filename, 'w') as f:
  2048. ___ = f.read()
  2049. except PermissionError:
  2050. self.inform.emit('[WARNING] %s' %
  2051. _("Permission denied, saving not possible.\n"
  2052. "Most likely another app is holding the file open and not accessible."))
  2053. return
  2054. except IOError:
  2055. App.log.debug('Creating a new file ...')
  2056. f = open(filename, 'w')
  2057. f.close()
  2058. except Exception:
  2059. e = sys.exc_info()[0]
  2060. App.log.error("Could not load the file.")
  2061. App.log.error(str(e))
  2062. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2063. return
  2064. # Save content
  2065. if filename.rpartition('.')[2].lower() == 'html':
  2066. file_content = content_to_save
  2067. else:
  2068. file_content = txt_content
  2069. try:
  2070. with open(filename, "w") as f:
  2071. f.write(file_content)
  2072. except Exception:
  2073. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2074. return
  2075. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2076. def register_recent(self, kind, filename):
  2077. """
  2078. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2079. dictionary.
  2080. :param kind: type of file that was opened
  2081. :param filename: the path and file name for the file that was opened
  2082. :return:
  2083. """
  2084. self.log.debug("register_recent()")
  2085. self.log.debug(" %s" % kind)
  2086. self.log.debug(" %s" % filename)
  2087. record = {'kind': str(kind), 'filename': str(filename)}
  2088. if record in self.recent:
  2089. return
  2090. if record in self.recent_projects:
  2091. return
  2092. if record['kind'] == 'project':
  2093. self.recent_projects.insert(0, record)
  2094. else:
  2095. self.recent.insert(0, record)
  2096. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2097. self.recent.pop()
  2098. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2099. self.recent_projects.pop()
  2100. try:
  2101. f = open(self.data_path + '/recent.json', 'w')
  2102. except IOError:
  2103. App.log.error("Failed to open recent items file for writing.")
  2104. self.inform.emit('[ERROR_NOTCL] %s' %
  2105. _('Failed to open recent files file for writing.'))
  2106. return
  2107. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2108. f.close()
  2109. try:
  2110. fp = open(self.data_path + '/recent_projects.json', 'w')
  2111. except IOError:
  2112. App.log.error("Failed to open recent items file for writing.")
  2113. self.inform.emit('[ERROR_NOTCL] %s' %
  2114. _('Failed to open recent projects file for writing.'))
  2115. return
  2116. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2117. fp.close()
  2118. # Re-build the recent items menu
  2119. self.setup_recent_items()
  2120. def on_about(self):
  2121. """
  2122. Displays the "about" dialog found in the Menu --> Help.
  2123. :return: None
  2124. """
  2125. self.defaults.report_usage("on_about")
  2126. version = self.version
  2127. version_date = self.version_date
  2128. beta = self.beta
  2129. class AboutDialog(QtWidgets.QDialog):
  2130. def __init__(self, app, parent=None):
  2131. QtWidgets.QDialog.__init__(self, parent)
  2132. self.app = app
  2133. # Icon and title
  2134. self.setWindowIcon(parent.app_icon)
  2135. self.setWindowTitle(_("About FlatCAM"))
  2136. self.resize(600, 200)
  2137. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2138. # self.setStyleSheet(
  2139. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2140. # "background-attachment: fixed"
  2141. # )
  2142. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2143. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2144. # palette = QtGui.QPalette()
  2145. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2146. # self.setPalette(palette)
  2147. logo = QtWidgets.QLabel()
  2148. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2149. title = QtWidgets.QLabel(
  2150. "<font size=8><B>FlatCAM</B></font><BR>"
  2151. "{title}<BR>"
  2152. "<BR>"
  2153. "<BR>"
  2154. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2155. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2156. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2157. "<B>{issue}</B></a><BR>".format(
  2158. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2159. devel=_("Development"),
  2160. down=_("DOWNLOAD"),
  2161. issue=_("Issue tracker"))
  2162. )
  2163. title.setOpenExternalLinks(True)
  2164. closebtn = QtWidgets.QPushButton(_("Close"))
  2165. tab_widget = QtWidgets.QTabWidget()
  2166. description_label = QtWidgets.QLabel(
  2167. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2168. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2169. version=version,
  2170. beta=('BETA' if beta else ''),
  2171. date=version_date,
  2172. arch=platform.architecture()[0])
  2173. )
  2174. description_label.setOpenExternalLinks(True)
  2175. lic_lbl_header = QtWidgets.QLabel(
  2176. '%s:<br>%s<br>' % (
  2177. _('Licensed under the MIT license'),
  2178. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2179. "http://www.opensource.org/licenses/mit-license.php</a>"
  2180. )
  2181. )
  2182. lic_lbl_header.setOpenExternalLinks(True)
  2183. lic_lbl_body = QtWidgets.QLabel(
  2184. _(
  2185. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2186. 'of this software and associated documentation files (the "Software"), to deal\n'
  2187. 'in the Software without restriction, including without limitation the rights\n'
  2188. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2189. 'copies of the Software, and to permit persons to whom the Software is\n'
  2190. 'furnished to do so, subject to the following conditions:\n\n'
  2191. 'The above copyright notice and this permission notice shall be included in\n'
  2192. 'all copies or substantial portions of the Software.\n\n'
  2193. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2194. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2195. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2196. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2197. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2198. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2199. 'THE SOFTWARE.'
  2200. )
  2201. )
  2202. attributions_label = QtWidgets.QLabel(
  2203. _(
  2204. 'Some of the icons used are from the following sources:<br>'
  2205. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2206. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2207. 'title="Flaticon">www.flaticon.com</a></div>'
  2208. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2209. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2210. )
  2211. )
  2212. attributions_label.setOpenExternalLinks(True)
  2213. # layouts
  2214. layout1 = QtWidgets.QVBoxLayout()
  2215. layout1_1 = QtWidgets.QHBoxLayout()
  2216. layout1_2 = QtWidgets.QHBoxLayout()
  2217. layout2 = QtWidgets.QHBoxLayout()
  2218. layout3 = QtWidgets.QHBoxLayout()
  2219. self.setLayout(layout1)
  2220. layout1.addLayout(layout1_1)
  2221. layout1.addLayout(layout1_2)
  2222. layout1.addLayout(layout2)
  2223. layout1.addLayout(layout3)
  2224. layout1_1.addStretch()
  2225. layout1_1.addWidget(description_label)
  2226. layout1_2.addWidget(tab_widget)
  2227. self.splash_tab = QtWidgets.QWidget()
  2228. self.splash_tab.setObjectName("splash_about")
  2229. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2230. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2231. tab_widget.addTab(self.splash_tab, _("Splash"))
  2232. self.programmmers_tab = QtWidgets.QWidget()
  2233. self.programmmers_tab.setObjectName("programmers_about")
  2234. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2235. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2236. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2237. self.translators_tab = QtWidgets.QWidget()
  2238. self.translators_tab.setObjectName("translators_about")
  2239. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2240. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2241. tab_widget.addTab(self.translators_tab, _("Translators"))
  2242. self.license_tab = QtWidgets.QWidget()
  2243. self.license_tab.setObjectName("license_about")
  2244. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2245. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2246. tab_widget.addTab(self.license_tab, _("License"))
  2247. self.attributions_tab = QtWidgets.QWidget()
  2248. self.attributions_tab.setObjectName("attributions_about")
  2249. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2250. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2251. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2252. self.splash_tab_layout.addWidget(logo, stretch=0)
  2253. self.splash_tab_layout.addWidget(title, stretch=1)
  2254. pal = QtGui.QPalette()
  2255. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2256. self.prog_grid_lay = QtWidgets.QGridLayout()
  2257. self.prog_grid_lay.setHorizontalSpacing(20)
  2258. self.prog_grid_lay.setColumnStretch(0, 0)
  2259. self.prog_grid_lay.setColumnStretch(2, 1)
  2260. prog_widget = QtWidgets.QWidget()
  2261. prog_widget.setLayout(self.prog_grid_lay)
  2262. prog_scroll = QtWidgets.QScrollArea()
  2263. prog_scroll.setWidget(prog_widget)
  2264. prog_scroll.setWidgetResizable(True)
  2265. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2266. prog_scroll.setPalette(pal)
  2267. self.programmmers_tab_layout.addWidget(prog_scroll)
  2268. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2269. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2270. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2271. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2315. self.translator_grid_lay = QtWidgets.QGridLayout()
  2316. self.translator_grid_lay.setColumnStretch(0, 0)
  2317. self.translator_grid_lay.setColumnStretch(1, 0)
  2318. self.translator_grid_lay.setColumnStretch(2, 1)
  2319. self.translator_grid_lay.setColumnStretch(3, 0)
  2320. # trans_widget = QtWidgets.QWidget()
  2321. # trans_widget.setLayout(self.translator_grid_lay)
  2322. # self.translators_tab_layout.addWidget(trans_widget)
  2323. # self.translators_tab_layout.addStretch()
  2324. trans_widget = QtWidgets.QWidget()
  2325. trans_widget.setLayout(self.translator_grid_lay)
  2326. trans_scroll = QtWidgets.QScrollArea()
  2327. trans_scroll.setWidget(trans_widget)
  2328. trans_scroll.setWidgetResizable(True)
  2329. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2330. trans_scroll.setPalette(pal)
  2331. self.translators_tab_layout.addWidget(trans_scroll)
  2332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2365. self.translator_grid_lay.setColumnStretch(0, 0)
  2366. self.translators_tab_layout.addStretch()
  2367. self.license_tab_layout.addWidget(lic_lbl_header)
  2368. self.license_tab_layout.addWidget(lic_lbl_body)
  2369. self.license_tab_layout.addStretch()
  2370. self.attributions_tab_layout.addWidget(attributions_label)
  2371. self.attributions_tab_layout.addStretch()
  2372. layout3.addStretch()
  2373. layout3.addWidget(closebtn)
  2374. closebtn.clicked.connect(self.accept)
  2375. AboutDialog(app=self, parent=self.ui).exec_()
  2376. def on_readme(self):
  2377. class AboutDialog(QtWidgets.QDialog):
  2378. def __init__(self, app, parent=None):
  2379. QtWidgets.QDialog.__init__(self, parent)
  2380. self.app = app
  2381. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2382. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2383. "<b>new features</b></a>"
  2384. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2385. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2386. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2387. # Icon and title
  2388. self.setWindowIcon(parent.app_icon)
  2389. self.setWindowTitle(_("Important Information's"))
  2390. self.resize(720, 330)
  2391. logo = QtWidgets.QLabel()
  2392. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2393. content = QtWidgets.QLabel(
  2394. "This program is %s and free in a very wide meaning of the word.<br>"
  2395. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2396. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2397. "you can <b>contribute</b> to the development yourself by:<br>"
  2398. "<ul>"
  2399. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2400. "<li>%s by providing the steps required to reproduce the bug</li>"
  2401. "<li>or by making a %s.</li>"
  2402. "</ul>"
  2403. "There are no strings attached.<br>"
  2404. "You don't have to make a %s, and it is totally optional but:"
  2405. "<ul>"
  2406. "<li>it will be welcomed with joy &#128077;</li>"
  2407. "<li>it will give me a reason to continue &#128513;</li>"
  2408. "</ul>" %
  2409. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2410. )
  2411. content.setOpenExternalLinks(True)
  2412. closebtn = QtWidgets.QPushButton(_("Close"))
  2413. # layouts
  2414. layout1 = QtWidgets.QVBoxLayout()
  2415. self.setLayout(layout1)
  2416. pal = QtGui.QPalette()
  2417. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2418. self.grid_lay = QtWidgets.QGridLayout()
  2419. self.grid_lay.setHorizontalSpacing(20)
  2420. self.grid_lay.setColumnStretch(0, 0)
  2421. self.grid_lay.setColumnStretch(1, 1)
  2422. content_widget = QtWidgets.QWidget()
  2423. content_widget.setLayout(self.grid_lay)
  2424. scroll_area = QtWidgets.QScrollArea()
  2425. scroll_area.setWidget(content_widget)
  2426. scroll_area.setWidgetResizable(True)
  2427. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2428. scroll_area.setPalette(pal)
  2429. self.grid_lay.addWidget(logo, 0, 0)
  2430. self.grid_lay.addWidget(content, 0, 1)
  2431. layout1.addWidget(scroll_area)
  2432. layout2 = QtWidgets.QHBoxLayout()
  2433. layout1.addLayout(layout2)
  2434. layout2.addStretch()
  2435. layout2.addWidget(closebtn)
  2436. closebtn.clicked.connect(self.accept)
  2437. AboutDialog(app=self, parent=self.ui).exec_()
  2438. def install_bookmarks(self, book_dict=None):
  2439. """
  2440. Install the bookmarks actions in the Help menu -> Bookmarks
  2441. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2442. :return: None
  2443. """
  2444. if book_dict is None:
  2445. self.defaults["global_bookmarks"].update(
  2446. {
  2447. '1': ['FlatCAM', "http://flatcam.org"],
  2448. '2': ['Backup Site', ""]
  2449. }
  2450. )
  2451. else:
  2452. self.defaults["global_bookmarks"].clear()
  2453. self.defaults["global_bookmarks"].update(book_dict)
  2454. # first try to disconnect if somehow they get connected from elsewhere
  2455. for act in self.ui.menuhelp_bookmarks.actions():
  2456. try:
  2457. act.triggered.disconnect()
  2458. except TypeError:
  2459. pass
  2460. # clear all actions except the last one who is the Bookmark manager
  2461. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2462. pass
  2463. else:
  2464. self.ui.menuhelp_bookmarks.removeAction(act)
  2465. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2466. if self.defaults["global_bookmarks"]:
  2467. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2468. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2469. # the JSON is first making the keys as strings (therefore I have to use strings too
  2470. # or do the conversion :(
  2471. # )
  2472. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2473. # the '10' entry jsut after '1' therefore ordering as strings
  2474. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2475. key=lambda x: int(x[0]))
  2476. for entry, bookmark in sorted_bookmarks:
  2477. title = bookmark[0]
  2478. weblink = bookmark[1]
  2479. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2480. act.setText(title)
  2481. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2482. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2483. if title == 'Backup Site' and weblink == "":
  2484. act.triggered.connect(self.on_backup_site)
  2485. else:
  2486. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2487. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2488. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2489. def on_bookmarks_manager(self):
  2490. """
  2491. Adds the bookmark manager in a Tab in Plot Area
  2492. :return:
  2493. """
  2494. for idx in range(self.ui.plot_tab_area.count()):
  2495. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2496. # there can be only one instance of Bookmark Manager at one time
  2497. return
  2498. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2499. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2500. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2501. # add the tab if it was closed
  2502. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2503. # delete the absolute and relative position and messages in the infobar
  2504. self.ui.position_label.setText("")
  2505. # self.ui.rel_position_label.setText("")
  2506. # Switch plot_area to preferences page
  2507. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2508. def on_backup_site(self):
  2509. msgbox = QtWidgets.QMessageBox()
  2510. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2511. "1. FlatCAM.org website is down\n"
  2512. "2. Someone forked FlatCAM project and wants to point\n"
  2513. "to his own website\n\n"
  2514. "If you can't get any informations about FlatCAM beta\n"
  2515. "use the YouTube channel link from the Help menu."))
  2516. msgbox.setWindowTitle(_("Alternative website"))
  2517. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2518. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2519. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2520. msgbox.setDefaultButton(bt_yes)
  2521. msgbox.exec_()
  2522. # response = msgbox.clickedButton()
  2523. def on_file_savedefaults(self):
  2524. """
  2525. Callback for menu item File->Save Defaults. Saves application default options
  2526. ``self.defaults`` to current_defaults.FlatConfig.
  2527. :return: None
  2528. """
  2529. self.preferencesUiManager.save_defaults()
  2530. def final_save(self):
  2531. """
  2532. Callback for doing a preferences save to file whenever the application is about to quit.
  2533. If the project has changes, it will ask the user to save the project.
  2534. :return: None
  2535. """
  2536. if self.save_in_progress:
  2537. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2538. return
  2539. if self.should_we_save and self.collection.get_list():
  2540. msgbox = QtWidgets.QMessageBox()
  2541. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2542. "\n"
  2543. "Do you want to Save the project?"))
  2544. msgbox.setWindowTitle(_("Save changes"))
  2545. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2546. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2547. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2548. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2549. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2550. msgbox.setDefaultButton(bt_yes)
  2551. msgbox.exec_()
  2552. response = msgbox.clickedButton()
  2553. if response == bt_yes:
  2554. try:
  2555. self.trayIcon.hide()
  2556. except Exception:
  2557. pass
  2558. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2559. elif response == bt_no:
  2560. try:
  2561. self.trayIcon.hide()
  2562. except Exception:
  2563. pass
  2564. self.quit_application()
  2565. elif response == bt_cancel:
  2566. return
  2567. else:
  2568. try:
  2569. self.trayIcon.hide()
  2570. except Exception:
  2571. pass
  2572. self.quit_application()
  2573. def quit_application(self):
  2574. """
  2575. Called (as a pyslot or not) when the application is quit.
  2576. :return: None
  2577. """
  2578. self.preferencesUiManager.save_defaults(silent=True)
  2579. log.debug("App.quit_application() --> App Defaults saved.")
  2580. if self.cmd_line_headless != 1:
  2581. # save app state to file
  2582. stgs = QSettings("Open Source", "FlatCAM")
  2583. stgs.setValue('saved_gui_state', self.ui.saveState())
  2584. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2585. stgs.setValue(
  2586. 'language',
  2587. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2588. )
  2589. stgs.setValue(
  2590. 'notebook_font_size',
  2591. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2592. )
  2593. stgs.setValue(
  2594. 'axis_font_size',
  2595. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2596. )
  2597. stgs.setValue(
  2598. 'textbox_font_size',
  2599. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2600. )
  2601. stgs.setValue(
  2602. 'hud_font_size',
  2603. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2604. )
  2605. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2606. stgs.setValue(
  2607. 'machinist',
  2608. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2609. )
  2610. # This will write the setting to the platform specific storage.
  2611. del stgs
  2612. log.debug("App.quit_application() --> App UI state saved.")
  2613. # try to quit the Socket opened by ArgsThread class
  2614. try:
  2615. self.new_launch.stop.emit()
  2616. except Exception as err:
  2617. log.debug("App.quit_application() --> %s" % str(err))
  2618. # try to quit the QThread that run ArgsThread class
  2619. try:
  2620. self.th.quit()
  2621. except Exception as e:
  2622. log.debug("App.quit_application() --> %s" % str(e))
  2623. # terminate workers
  2624. self.workers.__del__()
  2625. # quit app by signalling for self.kill_app() method
  2626. # self.close_app_signal.emit()
  2627. QtWidgets.qApp.quit()
  2628. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2629. # we use the following command
  2630. minor_v = sys.version_info.minor
  2631. if minor_v < 8:
  2632. sys.exit(0)
  2633. else:
  2634. os._exit(0) # fix to work with Python 3.8
  2635. @staticmethod
  2636. def kill_app():
  2637. QtWidgets.qApp.quit()
  2638. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2639. # we use the following command
  2640. sys.exit(0)
  2641. def on_portable_checked(self, state):
  2642. """
  2643. Callback called when the checkbox in Preferences GUI is checked.
  2644. It will set the application as portable by creating the preferences and recent files in the
  2645. 'config' folder found in the FlatCAM installation folder.
  2646. :param state: boolean, the state of the checkbox when clicked/checked
  2647. :return:
  2648. """
  2649. line_no = 0
  2650. data = None
  2651. if sys.platform != 'win32':
  2652. # this won't work in Linux or MacOS
  2653. return
  2654. # test if the app was frozen and choose the path for the configuration file
  2655. if getattr(sys, "frozen", False) is True:
  2656. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2657. else:
  2658. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2659. config_file = current_data_path + '\\configuration.txt'
  2660. try:
  2661. with open(config_file, 'r') as f:
  2662. try:
  2663. data = f.readlines()
  2664. except Exception as e:
  2665. log.debug('App.__init__() -->%s' % str(e))
  2666. return
  2667. except FileNotFoundError:
  2668. pass
  2669. for line in data:
  2670. line = line.strip('\n')
  2671. param = str(line).rpartition('=')
  2672. if param[0] == 'portable':
  2673. break
  2674. line_no += 1
  2675. if state:
  2676. data[line_no] = 'portable=True\n'
  2677. # create the new defauults files
  2678. # create current_defaults.FlatConfig file if there is none
  2679. try:
  2680. f = open(current_data_path + '/current_defaults.FlatConfig')
  2681. f.close()
  2682. except IOError:
  2683. App.log.debug('Creating empty current_defaults.FlatConfig')
  2684. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2685. json.dump({}, f)
  2686. f.close()
  2687. # create factory_defaults.FlatConfig file if there is none
  2688. try:
  2689. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2690. f.close()
  2691. except IOError:
  2692. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2693. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2694. json.dump({}, f)
  2695. f.close()
  2696. try:
  2697. f = open(current_data_path + '/recent.json')
  2698. f.close()
  2699. except IOError:
  2700. App.log.debug('Creating empty recent.json')
  2701. f = open(current_data_path + '/recent.json', 'w')
  2702. json.dump([], f)
  2703. f.close()
  2704. try:
  2705. fp = open(current_data_path + '/recent_projects.json')
  2706. fp.close()
  2707. except IOError:
  2708. App.log.debug('Creating empty recent_projects.json')
  2709. fp = open(current_data_path + '/recent_projects.json', 'w')
  2710. json.dump([], fp)
  2711. fp.close()
  2712. # save the current defaults to the new defaults file
  2713. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2714. else:
  2715. data[line_no] = 'portable=False\n'
  2716. with open(config_file, 'w') as f:
  2717. f.writelines(data)
  2718. def on_register_files(self, obj_type=None):
  2719. """
  2720. Called whenever there is a need to register file extensions with FlatCAM.
  2721. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2722. :param obj_type: the type of object to be register for.
  2723. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2724. :return: None
  2725. """
  2726. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2727. new_reg_path = 'Software\\Classes\\'
  2728. # find if the current user is admin
  2729. try:
  2730. is_admin = os.getuid() == 0
  2731. except AttributeError:
  2732. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2733. if is_admin is True:
  2734. root_path = winreg.HKEY_LOCAL_MACHINE
  2735. else:
  2736. root_path = winreg.HKEY_CURRENT_USER
  2737. # create the keys
  2738. def set_reg(name, root_pth, new_reg_path, value):
  2739. try:
  2740. winreg.CreateKey(root_pth, new_reg_path)
  2741. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2742. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2743. return True
  2744. except WindowsError:
  2745. return False
  2746. # delete key in registry
  2747. def delete_reg(root_pth, reg_path, key_to_del):
  2748. key_to_del_path = reg_path + key_to_del
  2749. try:
  2750. winreg.DeleteKey(root_pth, key_to_del_path)
  2751. return True
  2752. except WindowsError:
  2753. return False
  2754. if obj_type is None or obj_type == 'excellon':
  2755. exc_list = \
  2756. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2757. exc_list = [x for x in exc_list if x != '']
  2758. # register all keys in the Preferences window
  2759. for ext in exc_list:
  2760. new_k = new_reg_path + '.%s' % ext
  2761. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2762. # and unregister those that are no longer in the Preferences windows but are in the file
  2763. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2764. if ext not in exc_list:
  2765. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2766. # now write the updated extensions to the self.defaults
  2767. # new_ext = ''
  2768. # for ext in exc_list:
  2769. # new_ext = new_ext + ext + ', '
  2770. # self.defaults["fa_excellon"] = new_ext
  2771. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2772. if obj_type is None or obj_type == 'gcode':
  2773. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2774. gco_list = [x for x in gco_list if x != '']
  2775. # register all keys in the Preferences window
  2776. for ext in gco_list:
  2777. new_k = new_reg_path + '.%s' % ext
  2778. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2779. # and unregister those that are no longer in the Preferences windows but are in the file
  2780. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2781. if ext not in gco_list:
  2782. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2783. # now write the updated extensions to the self.defaults
  2784. # new_ext = ''
  2785. # for ext in gco_list:
  2786. # new_ext = new_ext + ext + ', '
  2787. # self.defaults["fa_gcode"] = new_ext
  2788. self.inform.emit('[success] %s' %
  2789. _("Selected GCode file extensions registered with FlatCAM."))
  2790. if obj_type is None or obj_type == 'gerber':
  2791. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2792. grb_list = [x for x in grb_list if x != '']
  2793. # register all keys in the Preferences window
  2794. for ext in grb_list:
  2795. new_k = new_reg_path + '.%s' % ext
  2796. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2797. # and unregister those that are no longer in the Preferences windows but are in the file
  2798. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2799. if ext not in grb_list:
  2800. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2801. # now write the updated extensions to the self.defaults
  2802. # new_ext = ''
  2803. # for ext in grb_list:
  2804. # new_ext = new_ext + ext + ', '
  2805. # self.defaults["fa_gerber"] = new_ext
  2806. self.inform.emit('[success] %s' %
  2807. _("Selected Gerber file extensions registered with FlatCAM."))
  2808. def add_extension(self, ext_type):
  2809. """
  2810. Add a file extension to the list for a specific object
  2811. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2812. :return:
  2813. """
  2814. if ext_type == 'excellon':
  2815. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2816. if new_ext == '':
  2817. return
  2818. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2819. if new_ext in old_val:
  2820. return
  2821. old_val.append(new_ext)
  2822. old_val.sort()
  2823. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2824. if ext_type == 'gcode':
  2825. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2826. if new_ext == '':
  2827. return
  2828. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2829. if new_ext in old_val:
  2830. return
  2831. old_val.append(new_ext)
  2832. old_val.sort()
  2833. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2834. if ext_type == 'gerber':
  2835. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2836. if new_ext == '':
  2837. return
  2838. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2839. if new_ext in old_val:
  2840. return
  2841. old_val.append(new_ext)
  2842. old_val.sort()
  2843. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2844. if ext_type == 'keyword':
  2845. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2846. if new_kw == '':
  2847. return
  2848. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2849. if new_kw in old_val:
  2850. return
  2851. old_val.append(new_kw)
  2852. old_val.sort()
  2853. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2854. # update the self.myKeywords so the model is updated
  2855. self.autocomplete_kw_list = \
  2856. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2857. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2858. self.shell._edit.set_model_data(self.myKeywords)
  2859. def del_extension(self, ext_type):
  2860. """
  2861. Remove a file extension from the list for a specific object
  2862. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2863. :return:
  2864. """
  2865. if ext_type == 'excellon':
  2866. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2867. if new_ext == '':
  2868. return
  2869. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2870. if new_ext not in old_val:
  2871. return
  2872. old_val.remove(new_ext)
  2873. old_val.sort()
  2874. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2875. if ext_type == 'gcode':
  2876. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2877. if new_ext == '':
  2878. return
  2879. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2880. if new_ext not in old_val:
  2881. return
  2882. old_val.remove(new_ext)
  2883. old_val.sort()
  2884. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2885. if ext_type == 'gerber':
  2886. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2887. if new_ext == '':
  2888. return
  2889. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2890. if new_ext not in old_val:
  2891. return
  2892. old_val.remove(new_ext)
  2893. old_val.sort()
  2894. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2895. if ext_type == 'keyword':
  2896. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2897. if new_kw == '':
  2898. return
  2899. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2900. if new_kw not in old_val:
  2901. return
  2902. old_val.remove(new_kw)
  2903. old_val.sort()
  2904. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2905. # update the self.myKeywords so the model is updated
  2906. self.autocomplete_kw_list = \
  2907. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2908. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2909. self.shell._edit.set_model_data(self.myKeywords)
  2910. def restore_extensions(self, ext_type):
  2911. """
  2912. Restore all file extensions associations with FlatCAM, for a specific object
  2913. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2914. :return:
  2915. """
  2916. if ext_type == 'excellon':
  2917. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2918. # for the ability to open Excellon files with .txt extension
  2919. new_exc_list = deepcopy(self.exc_list)
  2920. try:
  2921. new_exc_list.remove('txt')
  2922. except ValueError:
  2923. pass
  2924. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2925. if ext_type == 'gcode':
  2926. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2927. if ext_type == 'gerber':
  2928. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2929. if ext_type == 'keyword':
  2930. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2931. # update the self.myKeywords so the model is updated
  2932. self.autocomplete_kw_list = self.default_keywords
  2933. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2934. self.shell._edit.set_model_data(self.myKeywords)
  2935. def delete_all_extensions(self, ext_type):
  2936. """
  2937. Delete all file extensions associations with FlatCAM, for a specific object
  2938. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2939. :return:
  2940. """
  2941. if ext_type == 'excellon':
  2942. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2943. if ext_type == 'gcode':
  2944. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2945. if ext_type == 'gerber':
  2946. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2947. if ext_type == 'keyword':
  2948. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2949. # update the self.myKeywords so the model is updated
  2950. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2951. self.shell._edit.set_model_data(self.myKeywords)
  2952. def on_edit_join(self, name=None):
  2953. """
  2954. Callback for Edit->Join. Joins the selected geometry objects into
  2955. a new one.
  2956. :return: None
  2957. """
  2958. self.defaults.report_usage("on_edit_join()")
  2959. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2960. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2961. geo_type_set = set()
  2962. objs = self.collection.get_selected()
  2963. if len(objs) < 2:
  2964. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2965. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2966. return 'fail'
  2967. for obj in objs:
  2968. geo_type_set.add(obj.multigeo)
  2969. # if len(geo_type_list) == 1 means that all list elements are the same
  2970. if len(geo_type_set) != 1:
  2971. self.inform.emit('[ERROR] %s' %
  2972. _("Failed join. The Geometry objects are of different types.\n"
  2973. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2974. "convert from one to another and retry joining \n"
  2975. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2976. "the result may not be what was expected. \n"
  2977. "Check the generated GCODE."))
  2978. return
  2979. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2980. if True in geo_type_set:
  2981. def initialize(geo_obj, app):
  2982. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2983. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2984. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2985. for v in geo_obj.tools.values():
  2986. v['data']['name'] = obj_name_multi
  2987. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2988. else:
  2989. def initialize(geo_obj, app):
  2990. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2991. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2992. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2993. for v in geo_obj.tools.values():
  2994. v['data']['name'] = obj_name_single
  2995. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2996. self.should_we_save = True
  2997. def on_edit_join_exc(self):
  2998. """
  2999. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3000. a new Excellon.
  3001. :return: None
  3002. """
  3003. self.defaults.report_usage("on_edit_join_exc()")
  3004. objs = self.collection.get_selected()
  3005. for obj in objs:
  3006. if not isinstance(obj, ExcellonObject):
  3007. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3008. return
  3009. if len(objs) < 2:
  3010. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3011. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3012. return 'fail'
  3013. def initialize(exc_obj, app):
  3014. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3015. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3016. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3017. self.should_we_save = True
  3018. def on_edit_join_grb(self):
  3019. """
  3020. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3021. a new Gerber object.
  3022. :return: None
  3023. """
  3024. self.defaults.report_usage("on_edit_join_grb()")
  3025. objs = self.collection.get_selected()
  3026. for obj in objs:
  3027. if not isinstance(obj, GerberObject):
  3028. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3029. return
  3030. if len(objs) < 2:
  3031. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3032. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3033. return 'fail'
  3034. def initialize(grb_obj, app):
  3035. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3036. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3037. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3038. self.should_we_save = True
  3039. def on_convert_singlegeo_to_multigeo(self):
  3040. """
  3041. Called for converting a Geometry object from single-geo to multi-geo.
  3042. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3043. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3044. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3045. the solid-geometry of that tool.
  3046. :return: None
  3047. """
  3048. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3049. obj = self.collection.get_active()
  3050. if obj is None:
  3051. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3052. return
  3053. if not isinstance(obj, GeometryObject):
  3054. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3055. return
  3056. obj.multigeo = True
  3057. for tooluid, dict_value in obj.tools.items():
  3058. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3059. if not isinstance(obj.solid_geometry, list):
  3060. obj.solid_geometry = [obj.solid_geometry]
  3061. # obj.solid_geometry[:] = []
  3062. obj.plot()
  3063. self.should_we_save = True
  3064. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3065. def on_convert_multigeo_to_singlegeo(self):
  3066. """
  3067. Called for converting a Geometry object from multi-geo to single-geo.
  3068. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3069. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3070. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3071. the solid-geometry of that tool.
  3072. :return: None
  3073. """
  3074. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3075. obj = self.collection.get_active()
  3076. if obj is None:
  3077. self.inform.emit('[ERROR_NOTCL] %s' %
  3078. _("Failed. Select a Geometry Object and try again."))
  3079. return
  3080. if not isinstance(obj, GeometryObject):
  3081. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3082. (_("Expected a GeometryObject, got"), type(obj)))
  3083. return
  3084. obj.multigeo = False
  3085. total_solid_geometry = []
  3086. for tooluid, dict_value in obj.tools.items():
  3087. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3088. # clear the original geometry
  3089. dict_value['solid_geometry'][:] = []
  3090. obj.solid_geometry = deepcopy(total_solid_geometry)
  3091. obj.plot()
  3092. self.should_we_save = True
  3093. self.inform.emit('[success] %s' %
  3094. _("A Geometry object was converted to SingleGeo type."))
  3095. def on_defaults_dict_change(self, field):
  3096. """
  3097. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3098. Edit -> Preferences tab window.
  3099. :param field: the key of the self.defaults dictionary that was changed.
  3100. :return: None
  3101. """
  3102. self.preferencesUiManager.defaults_write_form_field(field=field)
  3103. if field == "units":
  3104. self.set_screen_units(self.defaults['units'])
  3105. def set_screen_units(self, units):
  3106. """
  3107. Set the FlatCAM units on the status bar.
  3108. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3109. :return: None
  3110. """
  3111. self.ui.units_label.setText("[" + units.lower() + "]")
  3112. def on_toggle_units_click(self):
  3113. try:
  3114. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3115. except (TypeError, AttributeError):
  3116. pass
  3117. if self.defaults["units"] == 'MM':
  3118. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3119. else:
  3120. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3121. self.on_toggle_units(no_pref=True)
  3122. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3123. lambda: self.on_toggle_units(no_pref=False))
  3124. def on_toggle_units(self, no_pref=False):
  3125. """
  3126. Callback for the Units radio-button change in the Preferences tab.
  3127. Changes the application's default units adn for the project too.
  3128. If changing the project's units, the change propagates to all of
  3129. the objects in the project.
  3130. :return: None
  3131. """
  3132. self.defaults.report_usage("on_toggle_units")
  3133. if self.toggle_units_ignore:
  3134. return
  3135. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3136. # If option is the same, then ignore
  3137. if new_units == self.defaults["units"].upper():
  3138. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3139. return
  3140. # Keys in self.defaults for which to scale their values
  3141. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3142. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "tools_iso_tool_vtipdia",
  3143. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3144. "gerber_editor_ma_high",
  3145. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3146. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3147. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3148. "excellon_feedrate_probe", "excellon_milling_dia",
  3149. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3150. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3151. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3152. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3153. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3154. "geometry_extracut_length", "geometry_z_pdepth",
  3155. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3156. 'cncjob_tooldia',
  3157. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3158. "tools_paintnewdia",
  3159. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3160. "tools_nccnewdia", "tools_ncc_offset_value",
  3161. "tools_2sided_drilldia",
  3162. "tools_film_boundary", "tools_film_scale_stroke",
  3163. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3164. "tools_cutout_depthperpass",
  3165. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3166. "tools_panelize_spacing_rows",
  3167. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3168. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3169. "tools_transform_buffer_dis",
  3170. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3171. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3172. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3173. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3174. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3175. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3176. "tools_cr_h2h_val", "tools_cr_dh_val",
  3177. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3178. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3179. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3180. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3181. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3182. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3183. "tools_copper_thieving_mask_clearance",
  3184. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3185. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3186. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3187. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3188. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3189. "tools_invert_margin",
  3190. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3191. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3192. def scale_defaults(sfactor):
  3193. for dim in dimensions:
  3194. if dim in [
  3195. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3196. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3197. 'tools_transform_mirror_point'
  3198. ]:
  3199. if self.defaults[dim] is None or self.defaults[dim] == '':
  3200. continue
  3201. try:
  3202. coordinates = self.defaults[dim].split(",")
  3203. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3204. coords_xy[0] *= sfactor
  3205. coords_xy[1] *= sfactor
  3206. self.defaults[dim] = "%.*f, %.*f" % (
  3207. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3208. except Exception as e:
  3209. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3210. elif dim in [
  3211. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3212. ]:
  3213. if self.defaults[dim] is None or self.defaults[dim] == '':
  3214. continue
  3215. try:
  3216. self.defaults[dim] = float(self.defaults[dim])
  3217. tools_diameters = [self.defaults[dim]]
  3218. except ValueError:
  3219. try:
  3220. tools_string = self.defaults[dim].split(",")
  3221. tools_diameters = [eval(a) for a in tools_string if a != '']
  3222. except Exception as e:
  3223. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3224. continue
  3225. self.defaults[dim] = ''
  3226. td_len = len(tools_diameters)
  3227. if td_len > 1:
  3228. for t in range(td_len):
  3229. tools_diameters[t] *= sfactor
  3230. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3231. else:
  3232. tools_diameters[0] *= sfactor
  3233. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3234. elif dim in ['global_gridx', 'global_gridy']:
  3235. # format the number of decimals to the one specified in self.decimals
  3236. try:
  3237. val = float(self.defaults[dim]) * sfactor
  3238. except Exception as e:
  3239. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3240. continue
  3241. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3242. else:
  3243. # the number of decimals for the rest is kept unchanged
  3244. if self.defaults[dim]:
  3245. try:
  3246. val = float(self.defaults[dim]) * sfactor
  3247. except Exception as e:
  3248. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3249. continue
  3250. self.defaults[dim] = val
  3251. # The scaling factor depending on choice of units.
  3252. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3253. # Changing project units. Warn user.
  3254. msgbox = QtWidgets.QMessageBox()
  3255. msgbox.setWindowTitle(_("Toggle Units"))
  3256. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3257. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3258. msgbox.setText(_("Changing the units of the project\n"
  3259. "will scale all objects.\n\n"
  3260. "Do you want to continue?"))
  3261. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3262. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3263. msgbox.setDefaultButton(bt_ok)
  3264. msgbox.exec_()
  3265. response = msgbox.clickedButton()
  3266. if response == bt_ok:
  3267. if no_pref is False:
  3268. self.preferencesUiManager.defaults_read_form()
  3269. scale_defaults(factor)
  3270. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3271. self.defaults["units"] = new_units
  3272. # update the defaults from form, some may assume that the conversion is enough and it's not
  3273. self.on_options_app2project()
  3274. # update the objects
  3275. for obj in self.collection.get_list():
  3276. obj.convert_units(new_units)
  3277. # make that the properties stored in the object are also updated
  3278. self.app_obj.object_changed.emit(obj)
  3279. # rebuild the object UI
  3280. obj.build_ui()
  3281. # change this only if the workspace is active
  3282. if self.defaults['global_workspace'] is True:
  3283. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3284. # adjust the grid values on the main toolbar
  3285. val_x = float(self.defaults['global_gridx']) * factor
  3286. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3287. current = self.collection.get_active()
  3288. if current is not None:
  3289. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3290. if not isinstance(current, GeometryObject):
  3291. current.to_form()
  3292. # replot all objects
  3293. self.plot_all()
  3294. # set the status labels to reflect the current FlatCAM units
  3295. self.set_screen_units(new_units)
  3296. # signal to the app that we changed the object properties and it should save the project
  3297. self.should_we_save = True
  3298. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3299. else:
  3300. # Undo toggling
  3301. self.toggle_units_ignore = True
  3302. if self.defaults['units'].upper() == 'MM':
  3303. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3304. else:
  3305. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3306. self.toggle_units_ignore = False
  3307. # store the grid values so they are not changed in the next step
  3308. val_x = float(self.defaults['global_gridx'])
  3309. val_y = float(self.defaults['global_gridy'])
  3310. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3311. self.preferencesUiManager.defaults_read_form()
  3312. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3313. # in self.defaults from the GUI elements but
  3314. # I don't want it for the grid values, so I update them here
  3315. self.defaults['global_gridx'] = val_x
  3316. self.defaults['global_gridy'] = val_y
  3317. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3318. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3319. def on_toggle_axis(self):
  3320. self.defaults.report_usage("on_toggle_axis()")
  3321. if self.toggle_axis is False:
  3322. if self.is_legacy is False:
  3323. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3324. parent=self.plotcanvas.view.scene)
  3325. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3326. parent=self.plotcanvas.view.scene)
  3327. else:
  3328. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3329. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3330. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3331. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3332. self.plotcanvas.canvas.draw()
  3333. self.inform.emit(_("Axis enabled."))
  3334. self.toggle_axis = True
  3335. else:
  3336. if self.is_legacy is False:
  3337. self.plotcanvas.v_line.parent = None
  3338. self.plotcanvas.h_line.parent = None
  3339. else:
  3340. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3341. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3342. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3343. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3344. self.plotcanvas.canvas.draw()
  3345. self.inform.emit(_("Axis disabled."))
  3346. self.toggle_axis = False
  3347. def on_toggle_hud(self):
  3348. new_state = False if self.plotcanvas.hud_enabled else True
  3349. self.plotcanvas.on_toggle_hud(state=new_state)
  3350. if new_state is False:
  3351. self.inform.emit(_("HUD disabled."))
  3352. else:
  3353. self.inform.emit(_("HUD enabled."))
  3354. def on_toggle_grid_lines(self):
  3355. self.defaults.report_usage("on_toggle_grd_lines()")
  3356. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3357. if tt_settings.contains("theme"):
  3358. theme = tt_settings.value('theme', type=str)
  3359. else:
  3360. theme = 'white'
  3361. if self.toggle_grid_lines is False:
  3362. if self.is_legacy is False:
  3363. if theme == 'white':
  3364. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3365. else:
  3366. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3367. else:
  3368. self.plotcanvas.axes.grid(True)
  3369. try:
  3370. self.plotcanvas.canvas.draw()
  3371. except IndexError:
  3372. pass
  3373. pass
  3374. self.inform.emit(_("Grid enabled."))
  3375. self.toggle_grid_lines = True
  3376. else:
  3377. if self.is_legacy is False:
  3378. if theme == 'white':
  3379. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3380. else:
  3381. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3382. else:
  3383. self.plotcanvas.axes.grid(False)
  3384. try:
  3385. self.plotcanvas.canvas.draw()
  3386. except IndexError:
  3387. pass
  3388. self.toggle_grid_lines = False
  3389. self.inform.emit(_("Grid disabled."))
  3390. if self.is_legacy is False:
  3391. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3392. # - perhaps is a bug in VisPy implementation
  3393. if self.grid_status():
  3394. self.app_cursor.enabled = False
  3395. self.app_cursor.enabled = True
  3396. else:
  3397. self.app_cursor.enabled = True
  3398. self.app_cursor.enabled = False
  3399. def on_tab_rmb_click(self, checked):
  3400. self.ui.notebook.set_detachable(val=checked)
  3401. self.defaults["global_tabs_detachable"] = checked
  3402. self.ui.plot_tab_area.set_detachable(val=checked)
  3403. self.defaults["global_tabs_detachable"] = checked
  3404. def on_tab_setup_context_menu(self):
  3405. initial_checked = self.defaults["global_tabs_detachable"]
  3406. action_name = str(_("Detachable Tabs"))
  3407. action = QtWidgets.QAction(self)
  3408. action.setCheckable(True)
  3409. action.setText(action_name)
  3410. action.setChecked(initial_checked)
  3411. self.ui.notebook.tabBar.addAction(action)
  3412. self.ui.plot_tab_area.tabBar.addAction(action)
  3413. try:
  3414. action.triggered.disconnect()
  3415. except TypeError:
  3416. pass
  3417. action.triggered.connect(self.on_tab_rmb_click)
  3418. def on_deselect_all(self):
  3419. self.collection.set_all_inactive()
  3420. self.delete_selection_shape()
  3421. def on_workspace_modified(self):
  3422. # self.save_defaults(silent=True)
  3423. self.plotcanvas.delete_workspace()
  3424. self.preferencesUiManager.defaults_read_form()
  3425. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3426. def on_workspace(self):
  3427. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3428. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3429. self.inform.emit(_("Workspace enabled."))
  3430. else:
  3431. self.plotcanvas.delete_workspace()
  3432. self.inform.emit(_("Workspace disabled."))
  3433. self.preferencesUiManager.defaults_read_form()
  3434. # self.save_defaults(silent=True)
  3435. def on_workspace_toggle(self):
  3436. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3437. try:
  3438. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3439. except TypeError:
  3440. pass
  3441. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3442. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3443. self.on_workspace()
  3444. def on_cursor_type(self, val):
  3445. """
  3446. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3447. :return: None
  3448. """
  3449. self.app_cursor.enabled = False
  3450. if val == 'small':
  3451. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3452. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3453. self.app_cursor = self.plotcanvas.new_cursor()
  3454. else:
  3455. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3456. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3457. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3458. if self.ui.grid_snap_btn.isChecked():
  3459. self.app_cursor.enabled = True
  3460. else:
  3461. self.app_cursor.enabled = False
  3462. def on_tool_add_keypress(self):
  3463. # ## Current application units in Upper Case
  3464. self.units = self.defaults['units'].upper()
  3465. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3466. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3467. if notebook_widget_name == 'selected_tab':
  3468. if self.collection.get_active().kind == 'geometry':
  3469. # Tool add works for Geometry only if Advanced is True in Preferences
  3470. if self.defaults["global_app_level"] == 'a':
  3471. tool_add_popup = FCInputDialog(title="New Tool ...",
  3472. text='Enter a Tool Diameter:',
  3473. min=0.0000, max=99.9999, decimals=4)
  3474. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3475. val, ok = tool_add_popup.get_value()
  3476. if ok:
  3477. if float(val) == 0:
  3478. self.inform.emit('[WARNING_NOTCL] %s' %
  3479. _("Please enter a tool diameter with non-zero value, in Float format."))
  3480. return
  3481. self.collection.get_active().on_tool_add(dia=float(val))
  3482. else:
  3483. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3484. else:
  3485. msgbox = QtWidgets.QMessageBox()
  3486. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3487. "Go to Preferences -> General - Show Advanced Options."))
  3488. msgbox.setWindowTitle("Tool adding ...")
  3489. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3490. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3491. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3492. msgbox.setDefaultButton(bt_ok)
  3493. msgbox.exec_()
  3494. # work only if the notebook tab on focus is the Tools_Tab
  3495. if notebook_widget_name == 'tool_tab':
  3496. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3497. # and only if the tool is NCC Tool
  3498. if tool_widget == self.ncclear_tool.toolName:
  3499. self.ncclear_tool.on_add_tool_by_key()
  3500. # and only if the tool is Paint Area Tool
  3501. elif tool_widget == self.paint_tool.toolName:
  3502. self.paint_tool.on_add_tool_by_key()
  3503. # and only if the tool is Solder Paste Dispensing Tool
  3504. elif tool_widget == self.paste_tool.toolName:
  3505. self.paste_tool.on_add_tool_by_key()
  3506. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3507. # See description below.
  3508. def on_delete_keypress(self):
  3509. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3510. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3511. if notebook_widget_name == 'selected_tab':
  3512. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3513. self.collection.get_active().on_tool_delete()
  3514. # work only if the notebook tab on focus is the Tools_Tab
  3515. elif notebook_widget_name == 'tool_tab':
  3516. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3517. # and only if the tool is NCC Tool
  3518. if tool_widget == self.ncclear_tool.toolName:
  3519. self.ncclear_tool.on_tool_delete()
  3520. # and only if the tool is Paint Tool
  3521. elif tool_widget == self.paint_tool.toolName:
  3522. self.paint_tool.on_tool_delete()
  3523. # and only if the tool is Solder Paste Dispensing Tool
  3524. elif tool_widget == self.paste_tool.toolName:
  3525. self.paste_tool.on_tool_delete()
  3526. else:
  3527. self.on_delete()
  3528. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3529. # some screens you have to be careful where you hover with your mouse.
  3530. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3531. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3532. # Complicated, I know :)
  3533. def on_delete(self, force_deletion=False):
  3534. """
  3535. Delete the currently selected FlatCAMObjs.
  3536. :param force_deletion: used by Tcl command
  3537. :return: None
  3538. """
  3539. self.defaults.report_usage("on_delete()")
  3540. response = None
  3541. bt_ok = None
  3542. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3543. # a geometry object before we update it.
  3544. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3545. and self.grb_editor.editor_active is False:
  3546. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3547. msgbox = QtWidgets.QMessageBox()
  3548. msgbox.setWindowTitle(_("Delete objects"))
  3549. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3550. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3551. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3552. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3553. "the selected objects?"))
  3554. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3555. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3556. msgbox.setDefaultButton(bt_ok)
  3557. msgbox.exec_()
  3558. response = msgbox.clickedButton()
  3559. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3560. response = bt_ok
  3561. if response == bt_ok:
  3562. if self.collection.get_active():
  3563. self.log.debug("App.on_delete()")
  3564. for obj_active in self.collection.get_selected():
  3565. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3566. if obj_active.kind == 'gerber':
  3567. for el in obj_active.mark_shapes:
  3568. obj_active.mark_shapes[el].clear(update=True)
  3569. obj_active.mark_shapes[el].enabled = False
  3570. # obj_active.mark_shapes[el] = None
  3571. del el
  3572. elif isinstance(obj_active, CNCJobObject):
  3573. try:
  3574. obj_active.text_col.enabled = False
  3575. del obj_active.text_col
  3576. obj_active.annotation.clear(update=True)
  3577. del obj_active.annotation
  3578. except AttributeError as e:
  3579. log.debug(
  3580. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3581. )
  3582. while self.collection.get_selected():
  3583. self.delete_first_selected()
  3584. self.inform.emit('%s...' % _("Object(s) deleted"))
  3585. # make sure that the selection shape is deleted, too
  3586. self.delete_selection_shape()
  3587. # if there are no longer objects delete also the exclusion areas shapes
  3588. if not self.collection.get_list():
  3589. self.exc_areas.clear_shapes()
  3590. else:
  3591. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3592. else:
  3593. self.inform.emit(_("Save the work in Editor and try again ..."))
  3594. def delete_first_selected(self):
  3595. # Keep this for later
  3596. try:
  3597. sel_obj = self.collection.get_active()
  3598. name = sel_obj.options["name"]
  3599. isPlotted = sel_obj.options["plot"]
  3600. except AttributeError:
  3601. self.log.debug("Nothing selected for deletion")
  3602. return
  3603. if self.is_legacy is True:
  3604. # Remove plot only if the object was plotted otherwise delaxes will fail
  3605. if isPlotted:
  3606. try:
  3607. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3608. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3609. except Exception as e:
  3610. log.debug("App.delete_first_selected() --> %s" % str(e))
  3611. self.plotcanvas.auto_adjust_axes()
  3612. # Remove from dictionary
  3613. self.collection.delete_active()
  3614. # Clear form
  3615. self.setup_component_editor()
  3616. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3617. def on_set_origin(self):
  3618. """
  3619. Set the origin to the left mouse click position
  3620. :return: None
  3621. """
  3622. # display the message for the user
  3623. # and ask him to click on the desired position
  3624. self.defaults.report_usage("on_set_origin()")
  3625. def origin_replot():
  3626. def worker_task():
  3627. with self.proc_container.new('%s...' % _("Plotting")):
  3628. for obj in self.collection.get_list():
  3629. obj.plot()
  3630. self.plotcanvas.fit_view()
  3631. if self.is_legacy:
  3632. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3633. else:
  3634. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3635. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3636. self.inform.emit(_('Click to set the origin ...'))
  3637. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3638. # first disconnect it as it may have been used by something else
  3639. try:
  3640. self.replot_signal.disconnect()
  3641. except TypeError:
  3642. pass
  3643. self.replot_signal[list].connect(origin_replot)
  3644. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3645. """
  3646. :param event:
  3647. :param location:
  3648. :param noplot:
  3649. :param use_thread:
  3650. :return:
  3651. """
  3652. noplot_sig = noplot
  3653. def worker_task():
  3654. with self.proc_container.new(_("Setting Origin...")):
  3655. obj_list = self.collection.get_list()
  3656. for obj in obj_list:
  3657. obj.offset((x, y))
  3658. self.app_obj.object_changed.emit(obj)
  3659. # Update the object bounding box options
  3660. a, b, c, d = obj.bounds()
  3661. obj.options['xmin'] = a
  3662. obj.options['ymin'] = b
  3663. obj.options['xmax'] = c
  3664. obj.options['ymax'] = d
  3665. self.inform.emit('[success] %s...' % _('Origin set'))
  3666. for obj in obj_list:
  3667. out_name = obj.options["name"]
  3668. if obj.kind == 'gerber':
  3669. obj.source_file = self.export_gerber(
  3670. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3671. elif obj.kind == 'excellon':
  3672. obj.source_file = self.export_excellon(
  3673. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3674. if noplot_sig is False:
  3675. self.replot_signal.emit([])
  3676. if location is not None:
  3677. if len(location) != 2:
  3678. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3679. return 'fail'
  3680. x, y = location
  3681. if use_thread is True:
  3682. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3683. else:
  3684. worker_task()
  3685. self.should_we_save = True
  3686. return
  3687. if event is not None and event.button == 1:
  3688. if self.is_legacy is False:
  3689. event_pos = event.pos
  3690. else:
  3691. event_pos = (event.xdata, event.ydata)
  3692. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3693. if self.grid_status():
  3694. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3695. else:
  3696. pos = pos_canvas
  3697. x = 0 - pos[0]
  3698. y = 0 - pos[1]
  3699. if use_thread is True:
  3700. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3701. else:
  3702. worker_task()
  3703. self.should_we_save = True
  3704. def on_move2origin(self, use_thread=True):
  3705. """
  3706. Move selected objects to origin.
  3707. :param use_thread: Control if to use threaded operation. Boolean.
  3708. :return:
  3709. """
  3710. def worker_task():
  3711. with self.proc_container.new(_("Moving to Origin...")):
  3712. obj_list = self.collection.get_selected()
  3713. if not obj_list:
  3714. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3715. return
  3716. xminlist = []
  3717. yminlist = []
  3718. # first get a bounding box to fit all
  3719. for obj in obj_list:
  3720. xmin, ymin, xmax, ymax = obj.bounds()
  3721. xminlist.append(xmin)
  3722. yminlist.append(ymin)
  3723. # get the minimum x,y for all objects selected
  3724. x = min(xminlist)
  3725. y = min(yminlist)
  3726. for obj in obj_list:
  3727. obj.offset((-x, -y))
  3728. self.app_obj.object_changed.emit(obj)
  3729. # Update the object bounding box options
  3730. a, b, c, d = obj.bounds()
  3731. obj.options['xmin'] = a
  3732. obj.options['ymin'] = b
  3733. obj.options['xmax'] = c
  3734. obj.options['ymax'] = d
  3735. for obj in obj_list:
  3736. obj.plot()
  3737. for obj in obj_list:
  3738. out_name = obj.options["name"]
  3739. if obj.kind == 'gerber':
  3740. obj.source_file = self.export_gerber(
  3741. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3742. elif obj.kind == 'excellon':
  3743. obj.source_file = self.export_excellon(
  3744. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3745. self.inform.emit('[success] %s...' % _('Origin set'))
  3746. if use_thread is True:
  3747. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3748. else:
  3749. worker_task()
  3750. self.should_we_save = True
  3751. def on_jump_to(self, custom_location=None, fit_center=True):
  3752. """
  3753. Jump to a location by setting the mouse cursor location.
  3754. :param custom_location: Jump to a specified point. (x, y) tuple.
  3755. :param fit_center: If to fit view. Boolean.
  3756. :return:
  3757. """
  3758. self.defaults.report_usage("on_jump_to()")
  3759. if not custom_location:
  3760. dia_box_location = None
  3761. try:
  3762. dia_box_location = eval(self.clipboard.text())
  3763. except Exception:
  3764. pass
  3765. if type(dia_box_location) == tuple:
  3766. dia_box_location = str(dia_box_location)
  3767. else:
  3768. dia_box_location = None
  3769. # dia_box = Dialog_box(title=_("Jump to ..."),
  3770. # label=_("Enter the coordinates in format X,Y:"),
  3771. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3772. # initial_text=dia_box_location)
  3773. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3774. label=_("Enter the coordinates in format X,Y:"),
  3775. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3776. initial_text=dia_box_location,
  3777. reference=self.defaults['global_jump_ref'])
  3778. if dia_box.ok is True:
  3779. try:
  3780. location = eval(dia_box.location)
  3781. if not isinstance(location, tuple):
  3782. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3783. return
  3784. if dia_box.reference == 'rel':
  3785. rel_x = self.mouse[0] + location[0]
  3786. rel_y = self.mouse[1] + location[1]
  3787. location = (rel_x, rel_y)
  3788. self.defaults['global_jump_ref'] = dia_box.reference
  3789. except Exception:
  3790. return
  3791. else:
  3792. return
  3793. else:
  3794. location = custom_location
  3795. self.jump_signal.emit(location)
  3796. if fit_center:
  3797. self.plotcanvas.fit_center(loc=location)
  3798. cursor = QtGui.QCursor()
  3799. if self.is_legacy is False:
  3800. # I don't know where those differences come from but they are constant for the current
  3801. # execution of the application and they are multiples of a value around 0.0263mm.
  3802. # In a random way sometimes they are more sometimes they are less
  3803. # if units == 'MM':
  3804. # cal_factor = 0.0263
  3805. # else:
  3806. # cal_factor = 0.0263 / 25.4
  3807. cal_location = (location[0], location[1])
  3808. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3809. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3810. j_pos = (
  3811. int(canvas_origin.x() + round(jump_loc[0])),
  3812. int(canvas_origin.y() + round(jump_loc[1]))
  3813. )
  3814. cursor.setPos(j_pos[0], j_pos[1])
  3815. else:
  3816. # find the canvas origin which is in the top left corner
  3817. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3818. # determine the coordinates for the lowest left point of the canvas
  3819. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3820. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3821. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3822. # canvas) and the point (width, height) is in the top-right location
  3823. loc = self.plotcanvas.axes.transData.transform_point(location)
  3824. j_pos = (
  3825. int(x0 + loc[0]),
  3826. int(y0 - loc[1])
  3827. )
  3828. cursor.setPos(j_pos[0], j_pos[1])
  3829. self.plotcanvas.mouse = [location[0], location[1]]
  3830. if self.defaults["global_cursor_color_enabled"] is True:
  3831. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3832. else:
  3833. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3834. if self.grid_status():
  3835. # Update cursor
  3836. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3837. symbol='++', edge_color=self.cursor_color_3D,
  3838. edge_width=self.defaults["global_cursor_width"],
  3839. size=self.defaults["global_cursor_size"])
  3840. # Set the relative position label
  3841. dx = location[0] - float(self.rel_point1[0])
  3842. dy = location[1] - float(self.rel_point1[1])
  3843. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3844. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3845. # # Set the position label
  3846. #
  3847. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3848. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3849. units = self.defaults["units"].lower()
  3850. self.plotcanvas.text_hud.text = \
  3851. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3852. dx, units, dy, units, location[0], units, location[1], units)
  3853. self.inform.emit('[success] %s' % _("Done."))
  3854. return location
  3855. def on_locate(self, obj, fit_center=True):
  3856. """
  3857. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3858. :param obj: The object on which to locate certain points
  3859. :param fit_center: If to fit view. Boolean.
  3860. :return: A point location. (x, y) tuple.
  3861. """
  3862. self.defaults.report_usage("on_locate()")
  3863. if obj is None:
  3864. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3865. return 'fail'
  3866. class DialogBoxChoice(QtWidgets.QDialog):
  3867. def __init__(self, title=None, icon=None, choice='bl'):
  3868. """
  3869. :param title: string with the window title
  3870. """
  3871. super(DialogBoxChoice, self).__init__()
  3872. self.ok = False
  3873. self.setWindowIcon(icon)
  3874. self.setWindowTitle(str(title))
  3875. self.form = QtWidgets.QFormLayout(self)
  3876. self.ref_radio = RadioSet([
  3877. {"label": _("Bottom-Left"), "value": "bl"},
  3878. {"label": _("Top-Left"), "value": "tl"},
  3879. {"label": _("Bottom-Right"), "value": "br"},
  3880. {"label": _("Top-Right"), "value": "tr"},
  3881. {"label": _("Center"), "value": "c"}
  3882. ], orientation='vertical', stretch=False)
  3883. self.ref_radio.set_value(choice)
  3884. self.form.addRow(self.ref_radio)
  3885. self.button_box = QtWidgets.QDialogButtonBox(
  3886. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3887. Qt.Horizontal, parent=self)
  3888. self.form.addRow(self.button_box)
  3889. self.button_box.accepted.connect(self.accept)
  3890. self.button_box.rejected.connect(self.reject)
  3891. if self.exec_() == QtWidgets.QDialog.Accepted:
  3892. self.ok = True
  3893. self.location_point = self.ref_radio.get_value()
  3894. else:
  3895. self.ok = False
  3896. self.location_point = None
  3897. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3898. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3899. choice=self.defaults['global_locate_pt'])
  3900. if dia_box.ok is True:
  3901. try:
  3902. location_point = dia_box.location_point
  3903. self.defaults['global_locate_pt'] = dia_box.location_point
  3904. except Exception:
  3905. return
  3906. else:
  3907. return
  3908. loc_b = obj.bounds()
  3909. if location_point == 'bl':
  3910. location = (loc_b[0], loc_b[1])
  3911. elif location_point == 'tl':
  3912. location = (loc_b[0], loc_b[3])
  3913. elif location_point == 'br':
  3914. location = (loc_b[2], loc_b[1])
  3915. elif location_point == 'tr':
  3916. location = (loc_b[2], loc_b[3])
  3917. else:
  3918. # center
  3919. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3920. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3921. location = (cx, cy)
  3922. self.locate_signal.emit(location, location_point)
  3923. if fit_center:
  3924. self.plotcanvas.fit_center(loc=location)
  3925. cursor = QtGui.QCursor()
  3926. if self.is_legacy is False:
  3927. # I don't know where those differences come from but they are constant for the current
  3928. # execution of the application and they are multiples of a value around 0.0263mm.
  3929. # In a random way sometimes they are more sometimes they are less
  3930. # if units == 'MM':
  3931. # cal_factor = 0.0263
  3932. # else:
  3933. # cal_factor = 0.0263 / 25.4
  3934. cal_location = (location[0], location[1])
  3935. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3936. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3937. j_pos = (
  3938. int(canvas_origin.x() + round(jump_loc[0])),
  3939. int(canvas_origin.y() + round(jump_loc[1]))
  3940. )
  3941. cursor.setPos(j_pos[0], j_pos[1])
  3942. else:
  3943. # find the canvas origin which is in the top left corner
  3944. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3945. # determine the coordinates for the lowest left point of the canvas
  3946. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3947. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3948. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3949. # canvas) and the point (width, height) is in the top-right location
  3950. loc = self.plotcanvas.axes.transData.transform_point(location)
  3951. j_pos = (
  3952. int(x0 + loc[0]),
  3953. int(y0 - loc[1])
  3954. )
  3955. cursor.setPos(j_pos[0], j_pos[1])
  3956. self.plotcanvas.mouse = [location[0], location[1]]
  3957. if self.defaults["global_cursor_color_enabled"] is True:
  3958. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3959. else:
  3960. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3961. if self.grid_status():
  3962. # Update cursor
  3963. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3964. symbol='++', edge_color=self.cursor_color_3D,
  3965. edge_width=self.defaults["global_cursor_width"],
  3966. size=self.defaults["global_cursor_size"])
  3967. # Set the relative position label
  3968. self.dx = location[0] - float(self.rel_point1[0])
  3969. self.dy = location[1] - float(self.rel_point1[1])
  3970. # Set the position label
  3971. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3972. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3973. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3974. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3975. units = self.defaults["units"].lower()
  3976. self.plotcanvas.text_hud.text = \
  3977. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3978. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3979. self.inform.emit('[success] %s' % _("Done."))
  3980. return location
  3981. def on_copy_command(self):
  3982. """
  3983. Will copy a selection of objects, creating new objects.
  3984. :return:
  3985. """
  3986. self.defaults.report_usage("on_copy_command()")
  3987. def initialize(obj_init, app):
  3988. """
  3989. :param obj_init: the new object
  3990. :type obj_init: class
  3991. :param app: An instance of the App class
  3992. :type app: App
  3993. :return: None
  3994. :rtype:
  3995. """
  3996. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3997. try:
  3998. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3999. except AttributeError:
  4000. pass
  4001. try:
  4002. obj_init.apertures = deepcopy(obj.apertures)
  4003. except AttributeError:
  4004. pass
  4005. try:
  4006. if obj.tools:
  4007. obj_init.tools = deepcopy(obj.tools)
  4008. except Exception as err:
  4009. log.debug("App.on_copy_command() --> %s" % str(err))
  4010. try:
  4011. obj_init.source_file = deepcopy(obj.source_file)
  4012. except (AttributeError, TypeError):
  4013. pass
  4014. def initialize_excellon(obj_init, app):
  4015. obj_init.source_file = deepcopy(obj.source_file)
  4016. obj_init.tools = deepcopy(obj.tools)
  4017. # drills are offset, so they need to be deep copied
  4018. obj_init.drills = deepcopy(obj.drills)
  4019. # slots are offset, so they need to be deep copied
  4020. obj_init.slots = deepcopy(obj.slots)
  4021. obj_init.create_geometry()
  4022. def initialize_script(obj_init, app_obj):
  4023. obj_init.source_file = deepcopy(obj.source_file)
  4024. def initialize_document(obj_init, app_obj):
  4025. obj_init.source_file = deepcopy(obj.source_file)
  4026. for obj in self.collection.get_selected():
  4027. obj_name = obj.options["name"]
  4028. try:
  4029. if isinstance(obj, ExcellonObject):
  4030. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4031. elif isinstance(obj, GerberObject):
  4032. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4033. elif isinstance(obj, GeometryObject):
  4034. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4035. elif isinstance(obj, ScriptObject):
  4036. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4037. elif isinstance(obj, DocumentObject):
  4038. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4039. except Exception as e:
  4040. return "Operation failed: %s" % str(e)
  4041. def on_copy_object2(self, custom_name):
  4042. def initialize_geometry(obj_init, app):
  4043. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4044. try:
  4045. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4046. except AttributeError:
  4047. pass
  4048. try:
  4049. obj_init.apertures = deepcopy(obj.apertures)
  4050. except AttributeError:
  4051. pass
  4052. try:
  4053. if obj.tools:
  4054. obj_init.tools = deepcopy(obj.tools)
  4055. except Exception as ee:
  4056. log.debug("on_copy_object2() --> %s" % str(ee))
  4057. def initialize_gerber(obj_init, app):
  4058. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4059. obj_init.apertures = deepcopy(obj.apertures)
  4060. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4061. def initialize_excellon(obj_init, app):
  4062. obj_init.tools = deepcopy(obj.tools)
  4063. # drills are offset, so they need to be deep copied
  4064. obj_init.drills = deepcopy(obj.drills)
  4065. # slots are offset, so they need to be deep copied
  4066. obj_init.slots = deepcopy(obj.slots)
  4067. obj_init.create_geometry()
  4068. for obj in self.collection.get_selected():
  4069. obj_name = obj.options["name"]
  4070. try:
  4071. if isinstance(obj, ExcellonObject):
  4072. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4073. elif isinstance(obj, GerberObject):
  4074. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4075. elif isinstance(obj, GeometryObject):
  4076. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4077. except Exception as er:
  4078. return "Operation failed: %s" % str(er)
  4079. def on_rename_object(self, text):
  4080. """
  4081. Will rename an object.
  4082. :param text: New name for the object.
  4083. :return:
  4084. """
  4085. self.defaults.report_usage("on_rename_object()")
  4086. named_obj = self.collection.get_active()
  4087. for obj in named_obj:
  4088. if obj is list:
  4089. self.on_rename_object(text)
  4090. else:
  4091. try:
  4092. obj.options['name'] = text
  4093. except Exception as e:
  4094. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4095. def convert_any2geo(self):
  4096. """
  4097. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4098. :return:
  4099. """
  4100. self.defaults.report_usage("convert_any2geo()")
  4101. def initialize(obj_init, app):
  4102. obj_init.solid_geometry = obj.solid_geometry
  4103. try:
  4104. obj_init.follow_geometry = obj.follow_geometry
  4105. except AttributeError:
  4106. pass
  4107. try:
  4108. obj_init.apertures = obj.apertures
  4109. except AttributeError:
  4110. pass
  4111. try:
  4112. if obj.tools:
  4113. obj_init.tools = obj.tools
  4114. except AttributeError:
  4115. pass
  4116. def initialize_excellon(obj_init, app):
  4117. # objs = self.collection.get_selected()
  4118. # GeometryObject.merge(objs, obj)
  4119. solid_geo = []
  4120. for tool in obj.tools:
  4121. for geo in obj.tools[tool]['solid_geometry']:
  4122. solid_geo.append(geo)
  4123. obj_init.solid_geometry = deepcopy(solid_geo)
  4124. if not self.collection.get_selected():
  4125. log.warning("App.convert_any2geo --> No object selected")
  4126. self.inform.emit('[WARNING_NOTCL] %s' %
  4127. _("No object is selected. Select an object and try again."))
  4128. return
  4129. for obj in self.collection.get_selected():
  4130. obj_name = obj.options["name"]
  4131. try:
  4132. if isinstance(obj, ExcellonObject):
  4133. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4134. else:
  4135. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4136. except Exception as e:
  4137. return "Operation failed: %s" % str(e)
  4138. def convert_any2gerber(self):
  4139. """
  4140. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4141. :return:
  4142. """
  4143. self.defaults.report_usage("convert_any2gerber()")
  4144. def initialize_geometry(obj_init, app):
  4145. apertures = {}
  4146. apid = 0
  4147. apertures[str(apid)] = {}
  4148. apertures[str(apid)]['geometry'] = []
  4149. for obj_orig in obj.solid_geometry:
  4150. new_elem = {}
  4151. new_elem['solid'] = obj_orig
  4152. try:
  4153. new_elem['follow'] = obj_orig.exterior
  4154. except AttributeError:
  4155. pass
  4156. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4157. apertures[str(apid)]['size'] = 0.0
  4158. apertures[str(apid)]['type'] = 'C'
  4159. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4160. obj_init.apertures = deepcopy(apertures)
  4161. def initialize_excellon(obj_init, app):
  4162. apertures = {}
  4163. apid = 10
  4164. for tool in obj.tools:
  4165. apertures[str(apid)] = {}
  4166. apertures[str(apid)]['geometry'] = []
  4167. for geo in obj.tools[tool]['solid_geometry']:
  4168. new_el = {}
  4169. new_el['solid'] = geo
  4170. new_el['follow'] = geo.exterior
  4171. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4172. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4173. apertures[str(apid)]['type'] = 'C'
  4174. apid += 1
  4175. # create solid_geometry
  4176. solid_geometry = []
  4177. for apid in apertures:
  4178. for geo_el in apertures[apid]['geometry']:
  4179. solid_geometry.append(geo_el['solid'])
  4180. solid_geometry = MultiPolygon(solid_geometry)
  4181. solid_geometry = solid_geometry.buffer(0.0000001)
  4182. obj_init.solid_geometry = deepcopy(solid_geometry)
  4183. obj_init.apertures = deepcopy(apertures)
  4184. # clear the working objects (perhaps not necessary due of Python GC)
  4185. apertures.clear()
  4186. if not self.collection.get_selected():
  4187. log.warning("App.convert_any2gerber --> 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("gerber", str(obj_name) + "_conv", initialize_excellon)
  4196. elif isinstance(obj, GeometryObject):
  4197. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4198. else:
  4199. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4200. except Exception as e:
  4201. return "Operation failed: %s" % str(e)
  4202. def abort_all_tasks(self):
  4203. """
  4204. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4205. on the first possible occasion.
  4206. :return:
  4207. """
  4208. if self.abort_flag is False:
  4209. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4210. self.abort_flag = True
  4211. self.cleanup.emit()
  4212. def app_is_idle(self):
  4213. if self.abort_flag:
  4214. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4215. self.abort_flag = False
  4216. def on_selectall(self):
  4217. """
  4218. Will draw a selection box shape around the selected objects.
  4219. :return:
  4220. """
  4221. self.defaults.report_usage("on_selectall()")
  4222. # delete the possible selection box around a possible selected object
  4223. self.delete_selection_shape()
  4224. for name in self.collection.get_names():
  4225. self.collection.set_active(name)
  4226. curr_sel_obj = self.collection.get_by_name(name)
  4227. # create the selection box around the selected object
  4228. if self.defaults['global_selection_shape'] is True:
  4229. self.draw_selection_shape(curr_sel_obj)
  4230. def on_preferences(self):
  4231. """
  4232. Adds the Preferences in a Tab in Plot Area
  4233. :return:
  4234. """
  4235. # add the tab if it was closed
  4236. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4237. # delete the absolute and relative position and messages in the infobar
  4238. self.ui.position_label.setText("")
  4239. # self.ui.rel_position_label.setText("")
  4240. # Switch plot_area to preferences page
  4241. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4242. # self.ui.show()
  4243. # detect changes in the preferences
  4244. for idx in range(self.ui.pref_tab_area.count()):
  4245. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4246. try:
  4247. try:
  4248. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4249. except (TypeError, AttributeError):
  4250. pass
  4251. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4252. except AttributeError:
  4253. pass
  4254. try:
  4255. try:
  4256. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4257. except (TypeError, AttributeError):
  4258. pass
  4259. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4260. except AttributeError:
  4261. pass
  4262. try:
  4263. try:
  4264. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4265. except (TypeError, AttributeError):
  4266. pass
  4267. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4268. except AttributeError:
  4269. pass
  4270. try:
  4271. try:
  4272. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4273. except (TypeError, AttributeError):
  4274. pass
  4275. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4276. except AttributeError:
  4277. pass
  4278. try:
  4279. try:
  4280. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4281. except (TypeError, AttributeError):
  4282. pass
  4283. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4284. except AttributeError:
  4285. pass
  4286. def on_tools_database(self, source='app'):
  4287. """
  4288. Adds the Tools Database in a Tab in Plot Area.
  4289. :return:
  4290. """
  4291. for idx in range(self.ui.plot_tab_area.count()):
  4292. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4293. # there can be only one instance of Tools Database at one time
  4294. return
  4295. if source == 'app':
  4296. self.tools_db_tab = ToolsDB2(
  4297. app=self,
  4298. parent=self.ui,
  4299. callback_on_edited=self.on_tools_db_edited,
  4300. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4301. )
  4302. elif source == 'ncc':
  4303. self.tools_db_tab = ToolsDB2(
  4304. app=self,
  4305. parent=self.ui,
  4306. callback_on_edited=self.on_tools_db_edited,
  4307. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4308. )
  4309. elif source == 'paint':
  4310. self.tools_db_tab = ToolsDB2(
  4311. app=self,
  4312. parent=self.ui,
  4313. callback_on_edited=self.on_tools_db_edited,
  4314. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4315. )
  4316. elif source == 'iso':
  4317. self.tools_db_tab = ToolsDB2(
  4318. app=self,
  4319. parent=self.ui,
  4320. callback_on_edited=self.on_tools_db_edited,
  4321. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4322. )
  4323. # add the tab if it was closed
  4324. try:
  4325. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4326. self.tools_db_tab.setObjectName("database_tab")
  4327. except Exception as e:
  4328. log.debug("App.on_tools_database() --> %s" % str(e))
  4329. return
  4330. # delete the absolute and relative position and messages in the infobar
  4331. self.ui.position_label.setText("")
  4332. # self.ui.rel_position_label.setText("")
  4333. # Switch plot_area to preferences page
  4334. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4335. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4336. self.tools_db_tab.ui_connect()
  4337. def on_tools_db_edited(self):
  4338. """
  4339. Executed whenever a tool is edited in Tools Database.
  4340. Will color the text of the Tools Database tab to Red color.
  4341. :return:
  4342. """
  4343. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4344. for idx in range(self.ui.plot_tab_area.count()):
  4345. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4346. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4347. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4348. self.tools_db_changed_flag = True
  4349. def on_geometry_tool_add_from_db_executed(self, tool):
  4350. """
  4351. Here add the tool from DB in the selected geometry object.
  4352. :return:
  4353. """
  4354. tool_from_db = deepcopy(tool)
  4355. obj = self.collection.get_active()
  4356. if isinstance(obj, GeometryObject):
  4357. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4358. # close the tab and delete it
  4359. for idx in range(self.ui.plot_tab_area.count()):
  4360. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4361. wdg = self.ui.plot_tab_area.widget(idx)
  4362. wdg.deleteLater()
  4363. self.ui.plot_tab_area.removeTab(idx)
  4364. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4365. else:
  4366. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4367. def on_plot_area_tab_closed(self, tab_obj_name):
  4368. """
  4369. Executed whenever a QTab is closed in the Plot Area.
  4370. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4371. :return:
  4372. """
  4373. if tab_obj_name == "preferences_tab":
  4374. self.preferencesUiManager.on_close_preferences_tab()
  4375. elif tab_obj_name == "database_tab":
  4376. # disconnect the signals from the table widget in tab
  4377. self.tools_db_tab.ui_disconnect()
  4378. if self.tools_db_changed_flag is True:
  4379. msgbox = QtWidgets.QMessageBox()
  4380. msgbox.setText(_("One or more Tools are edited.\n"
  4381. "Do you want to update the Tools Database?"))
  4382. msgbox.setWindowTitle(_("Save Tools Database"))
  4383. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4384. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4385. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4386. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4387. msgbox.setDefaultButton(bt_yes)
  4388. msgbox.exec_()
  4389. response = msgbox.clickedButton()
  4390. if response == bt_yes:
  4391. self.tools_db_tab.on_save_tools_db()
  4392. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4393. else:
  4394. self.tools_db_changed_flag = False
  4395. self.inform.emit('')
  4396. return
  4397. self.tools_db_tab.deleteLater()
  4398. elif tab_obj_name == "text_editor_tab":
  4399. self.toggle_codeeditor = False
  4400. elif tab_obj_name == "bookmarks_tab":
  4401. self.book_dialog_tab.rebuild_actions()
  4402. self.book_dialog_tab.deleteLater()
  4403. else:
  4404. return
  4405. # def on_plotarea_tab_closed(self, tab_idx):
  4406. # """
  4407. #
  4408. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4409. # :return:
  4410. # """
  4411. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4412. #
  4413. # if widget is not None:
  4414. # widget.deleteLater()
  4415. # self.ui.plot_tab_area.removeTab(tab_idx)
  4416. def on_flipy(self):
  4417. """
  4418. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4419. :return:
  4420. """
  4421. self.defaults.report_usage("on_flipy()")
  4422. obj_list = self.collection.get_selected()
  4423. xminlist = []
  4424. yminlist = []
  4425. xmaxlist = []
  4426. ymaxlist = []
  4427. if not obj_list:
  4428. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4429. else:
  4430. try:
  4431. # first get a bounding box to fit all
  4432. for obj in obj_list:
  4433. xmin, ymin, xmax, ymax = obj.bounds()
  4434. xminlist.append(xmin)
  4435. yminlist.append(ymin)
  4436. xmaxlist.append(xmax)
  4437. ymaxlist.append(ymax)
  4438. # get the minimum x,y and maximum x,y for all objects selected
  4439. xminimal = min(xminlist)
  4440. yminimal = min(yminlist)
  4441. xmaximal = max(xmaxlist)
  4442. ymaximal = max(ymaxlist)
  4443. px = 0.5 * (xminimal + xmaximal)
  4444. py = 0.5 * (yminimal + ymaximal)
  4445. # execute mirroring
  4446. for obj in obj_list:
  4447. obj.mirror('X', [px, py])
  4448. obj.plot()
  4449. self.app_obj.object_changed.emit(obj)
  4450. self.inform.emit('[success] %s' %
  4451. _("Flip on Y axis done."))
  4452. except Exception as e:
  4453. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4454. return
  4455. def on_flipx(self):
  4456. """
  4457. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4458. :return:
  4459. """
  4460. self.defaults.report_usage("on_flipx()")
  4461. obj_list = self.collection.get_selected()
  4462. xminlist = []
  4463. yminlist = []
  4464. xmaxlist = []
  4465. ymaxlist = []
  4466. if not obj_list:
  4467. self.inform.emit('[WARNING_NOTCL] %s' %
  4468. _("No object selected to Flip on X axis."))
  4469. else:
  4470. try:
  4471. # first get a bounding box to fit all
  4472. for obj in obj_list:
  4473. xmin, ymin, xmax, ymax = obj.bounds()
  4474. xminlist.append(xmin)
  4475. yminlist.append(ymin)
  4476. xmaxlist.append(xmax)
  4477. ymaxlist.append(ymax)
  4478. # get the minimum x,y and maximum x,y for all objects selected
  4479. xminimal = min(xminlist)
  4480. yminimal = min(yminlist)
  4481. xmaximal = max(xmaxlist)
  4482. ymaximal = max(ymaxlist)
  4483. px = 0.5 * (xminimal + xmaximal)
  4484. py = 0.5 * (yminimal + ymaximal)
  4485. # execute mirroring
  4486. for obj in obj_list:
  4487. obj.mirror('Y', [px, py])
  4488. obj.plot()
  4489. self.app_obj.object_changed.emit(obj)
  4490. self.inform.emit('[success] %s' %
  4491. _("Flip on X axis done."))
  4492. except Exception as e:
  4493. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4494. return
  4495. def on_rotate(self, silent=False, preset=None):
  4496. """
  4497. Executed when Options -> Rotate Selection menu entry is clicked.
  4498. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4499. :param preset: A value to be used as predefined angle for rotation.
  4500. :return:
  4501. """
  4502. self.defaults.report_usage("on_rotate()")
  4503. obj_list = self.collection.get_selected()
  4504. xminlist = []
  4505. yminlist = []
  4506. xmaxlist = []
  4507. ymaxlist = []
  4508. if not obj_list:
  4509. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4510. else:
  4511. if silent is False:
  4512. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4513. min=-360, max=360, decimals=4,
  4514. init_val=float(self.defaults['tools_transform_rotate']))
  4515. num, ok = rotatebox.get_value()
  4516. else:
  4517. num = preset
  4518. ok = True
  4519. if ok:
  4520. try:
  4521. # first get a bounding box to fit all
  4522. for obj in obj_list:
  4523. xmin, ymin, xmax, ymax = obj.bounds()
  4524. xminlist.append(xmin)
  4525. yminlist.append(ymin)
  4526. xmaxlist.append(xmax)
  4527. ymaxlist.append(ymax)
  4528. # get the minimum x,y and maximum x,y for all objects selected
  4529. xminimal = min(xminlist)
  4530. yminimal = min(yminlist)
  4531. xmaximal = max(xmaxlist)
  4532. ymaximal = max(ymaxlist)
  4533. px = 0.5 * (xminimal + xmaximal)
  4534. py = 0.5 * (yminimal + ymaximal)
  4535. for sel_obj in obj_list:
  4536. sel_obj.rotate(-float(num), point=(px, py))
  4537. sel_obj.plot()
  4538. self.app_obj.object_changed.emit(sel_obj)
  4539. self.inform.emit('[success] %s' % _("Rotation done."))
  4540. except Exception as e:
  4541. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4542. return
  4543. def on_skewx(self):
  4544. """
  4545. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4546. :return:
  4547. """
  4548. self.defaults.report_usage("on_skewx()")
  4549. obj_list = self.collection.get_selected()
  4550. xminlist = []
  4551. yminlist = []
  4552. if not obj_list:
  4553. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4554. else:
  4555. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4556. min=-360, max=360, decimals=4,
  4557. init_val=float(self.defaults['tools_transform_skew_x']))
  4558. num, ok = skewxbox.get_value()
  4559. if ok:
  4560. # first get a bounding box to fit all
  4561. for obj in obj_list:
  4562. xmin, ymin, xmax, ymax = obj.bounds()
  4563. xminlist.append(xmin)
  4564. yminlist.append(ymin)
  4565. # get the minimum x,y and maximum x,y for all objects selected
  4566. xminimal = min(xminlist)
  4567. yminimal = min(yminlist)
  4568. for obj in obj_list:
  4569. obj.skew(num, 0, point=(xminimal, yminimal))
  4570. obj.plot()
  4571. self.app_obj.object_changed.emit(obj)
  4572. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4573. def on_skewy(self):
  4574. """
  4575. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4576. :return:
  4577. """
  4578. self.defaults.report_usage("on_skewy()")
  4579. obj_list = self.collection.get_selected()
  4580. xminlist = []
  4581. yminlist = []
  4582. if not obj_list:
  4583. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4584. else:
  4585. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4586. min=-360, max=360, decimals=4,
  4587. init_val=float(self.defaults['tools_transform_skew_y']))
  4588. num, ok = skewybox.get_value()
  4589. if ok:
  4590. # first get a bounding box to fit all
  4591. for obj in obj_list:
  4592. xmin, ymin, xmax, ymax = obj.bounds()
  4593. xminlist.append(xmin)
  4594. yminlist.append(ymin)
  4595. # get the minimum x,y and maximum x,y for all objects selected
  4596. xminimal = min(xminlist)
  4597. yminimal = min(yminlist)
  4598. for obj in obj_list:
  4599. obj.skew(0, num, point=(xminimal, yminimal))
  4600. obj.plot()
  4601. self.app_obj.object_changed.emit(obj)
  4602. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4603. def on_plots_updated(self):
  4604. """
  4605. Callback used to report when the plots have changed.
  4606. Adjust axes and zooms to fit.
  4607. :return: None
  4608. """
  4609. if self.is_legacy is False:
  4610. self.plotcanvas.update()
  4611. else:
  4612. self.plotcanvas.auto_adjust_axes()
  4613. self.on_zoom_fit()
  4614. self.collection.update_view()
  4615. # self.inform.emit(_("Plots updated ..."))
  4616. def on_toolbar_replot(self):
  4617. """
  4618. Callback for toolbar button. Re-plots all objects.
  4619. :return: None
  4620. """
  4621. self.log.debug("on_toolbar_replot()")
  4622. try:
  4623. self.collection.get_active().read_form()
  4624. except AttributeError:
  4625. self.log.debug("on_toolbar_replot(): AttributeError")
  4626. pass
  4627. self.plot_all()
  4628. def grid_status(self):
  4629. return True if self.ui.grid_snap_btn.isChecked() else False
  4630. def populate_cmenu_grids(self):
  4631. units = self.defaults['units'].lower()
  4632. # for act in self.ui.cmenu_gridmenu.actions():
  4633. # act.triggered.disconnect()
  4634. self.ui.cmenu_gridmenu.clear()
  4635. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4636. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4637. _("Grid On/Off"))
  4638. grid_toggle.setCheckable(True)
  4639. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4640. self.ui.cmenu_gridmenu.addSeparator()
  4641. for grid in sorted_list:
  4642. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4643. "%s" % str(grid))
  4644. action.triggered.connect(self.set_grid)
  4645. self.ui.cmenu_gridmenu.addSeparator()
  4646. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4647. _("Add"))
  4648. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4649. _("Delete"))
  4650. grid_add.triggered.connect(self.on_grid_add)
  4651. grid_delete.triggered.connect(self.on_grid_delete)
  4652. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4653. def set_grid(self):
  4654. menu_action = self.sender()
  4655. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4656. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4657. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4658. def on_grid_add(self):
  4659. # ## Current application units in lower Case
  4660. units = self.defaults['units'].lower()
  4661. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4662. text=_('Enter a Grid Value:'),
  4663. min=0.0000, max=99.9999, decimals=4)
  4664. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4665. val, ok = grid_add_popup.get_value()
  4666. if ok:
  4667. if float(val) == 0:
  4668. self.inform.emit('[WARNING_NOTCL] %s' %
  4669. _("Please enter a grid value with non-zero value, in Float format."))
  4670. return
  4671. else:
  4672. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4673. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4674. self.inform.emit('[success] %s...' % _("New Grid added"))
  4675. else:
  4676. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4677. else:
  4678. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4679. def on_grid_delete(self):
  4680. # ## Current application units in lower Case
  4681. units = self.defaults['units'].lower()
  4682. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4683. text='Enter a Grid Value:',
  4684. min=0.0000, max=99.9999, decimals=4)
  4685. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4686. val, ok = grid_del_popup.get_value()
  4687. if ok:
  4688. if float(val) == 0:
  4689. self.inform.emit('[WARNING_NOTCL] %s' %
  4690. _("Please enter a grid value with non-zero value, in Float format."))
  4691. return
  4692. else:
  4693. try:
  4694. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4695. except ValueError:
  4696. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4697. return
  4698. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4699. else:
  4700. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4701. def on_shortcut_list(self):
  4702. self.defaults.report_usage("on_shortcut_list()")
  4703. # add the tab if it was closed
  4704. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4705. # delete the absolute and relative position and messages in the infobar
  4706. self.ui.position_label.setText("")
  4707. # self.ui.rel_position_label.setText("")
  4708. # Switch plot_area to preferences page
  4709. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4710. # self.ui.show()
  4711. def on_select_tab(self, name):
  4712. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4713. if self.ui.splitter.sizes()[0] == 0:
  4714. self.ui.splitter.setSizes([1, 1])
  4715. else:
  4716. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4717. self.ui.splitter.setSizes([0, 1])
  4718. if name == 'project':
  4719. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4720. elif name == 'selected':
  4721. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4722. elif name == 'tool':
  4723. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4724. def on_copy_name(self):
  4725. self.defaults.report_usage("on_copy_name()")
  4726. obj = self.collection.get_active()
  4727. try:
  4728. name = obj.options["name"]
  4729. except AttributeError:
  4730. log.debug("on_copy_name() --> No object selected to copy it's name")
  4731. self.inform.emit('[WARNING_NOTCL]%s' %
  4732. _(" No object selected to copy it's name"))
  4733. return
  4734. self.clipboard.setText(name)
  4735. self.inform.emit(_("Name copied on clipboard ..."))
  4736. def on_mouse_click_over_plot(self, event):
  4737. """
  4738. Default actions are:
  4739. :param event: Contains information about the event, like which button
  4740. was clicked, the pixel coordinates and the axes coordinates.
  4741. :return: None
  4742. """
  4743. self.pos = []
  4744. if self.is_legacy is False:
  4745. event_pos = event.pos
  4746. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4747. # # Set the mouse button for panning
  4748. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4749. else:
  4750. event_pos = (event.xdata, event.ydata)
  4751. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4752. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4753. # So it can receive key presses
  4754. self.plotcanvas.native.setFocus()
  4755. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4756. if self.grid_status():
  4757. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4758. else:
  4759. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4760. try:
  4761. if event.button == 1:
  4762. # Reset here the relative coordinates so there is a new reference on the click position
  4763. if self.rel_point1 is None:
  4764. self.rel_point1 = self.pos
  4765. else:
  4766. self.rel_point2 = copy(self.rel_point1)
  4767. self.rel_point1 = self.pos
  4768. self.on_mouse_move_over_plot(event, origin_click=True)
  4769. except Exception as e:
  4770. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4771. def on_mouse_double_click_over_plot(self, event):
  4772. if event.button == 1:
  4773. self.doubleclick = True
  4774. def on_mouse_move_over_plot(self, event, origin_click=None):
  4775. """
  4776. Callback for the mouse motion event over the plot.
  4777. :param event: Contains information about the event.
  4778. :param origin_click
  4779. :return: None
  4780. """
  4781. if self.is_legacy is False:
  4782. event_pos = event.pos
  4783. if self.defaults["global_pan_button"] == '2':
  4784. pan_button = 2
  4785. else:
  4786. pan_button = 3
  4787. self.event_is_dragging = event.is_dragging
  4788. else:
  4789. event_pos = (event.xdata, event.ydata)
  4790. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4791. if self.defaults["global_pan_button"] == '2':
  4792. pan_button = 3
  4793. else:
  4794. pan_button = 2
  4795. self.event_is_dragging = self.plotcanvas.is_dragging
  4796. # So it can receive key presses but not when the Tcl Shell is active
  4797. if not self.ui.shell_dock.isVisible():
  4798. if not self.plotcanvas.native.hasFocus():
  4799. self.plotcanvas.native.setFocus()
  4800. self.pos_jump = event_pos
  4801. self.ui.popMenu.mouse_is_panning = False
  4802. if origin_click is None:
  4803. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4804. if event.button == pan_button and self.event_is_dragging == 1:
  4805. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4806. if self.ui.popMenu.popup_active:
  4807. self.ui.popMenu.popup_active = False
  4808. return
  4809. self.ui.popMenu.mouse_is_panning = True
  4810. return
  4811. if self.rel_point1 is not None:
  4812. try: # May fail in case mouse not within axes
  4813. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4814. if pos_canvas[0] is None or pos_canvas[1] is None:
  4815. return
  4816. if self.grid_status():
  4817. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4818. # Update cursor
  4819. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4820. symbol='++', edge_color=self.cursor_color_3D,
  4821. edge_width=self.defaults["global_cursor_width"],
  4822. size=self.defaults["global_cursor_size"])
  4823. else:
  4824. pos = (pos_canvas[0], pos_canvas[1])
  4825. self.dx = pos[0] - float(self.rel_point1[0])
  4826. self.dy = pos[1] - float(self.rel_point1[1])
  4827. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4828. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4829. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4830. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4831. units = self.defaults["units"].lower()
  4832. self.plotcanvas.text_hud.text = \
  4833. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4834. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4835. self.mouse = [pos[0], pos[1]]
  4836. # if the mouse is moved and the LMB is clicked then the action is a selection
  4837. if self.event_is_dragging == 1 and event.button == 1:
  4838. self.delete_selection_shape()
  4839. if self.dx < 0:
  4840. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4841. face_color=self.defaults['global_alt_sel_fill'])
  4842. self.selection_type = False
  4843. elif self.dx >= 0:
  4844. self.draw_moving_selection_shape(self.pos, pos)
  4845. self.selection_type = True
  4846. else:
  4847. self.selection_type = None
  4848. else:
  4849. self.selection_type = None
  4850. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4851. if self.defaults['global_hover']:
  4852. for obj in self.collection.get_list():
  4853. try:
  4854. # select the object(s) only if it is enabled (plotted)
  4855. if obj.options['plot']:
  4856. if obj not in self.collection.get_selected():
  4857. poly_obj = Polygon(
  4858. [(obj.options['xmin'], obj.options['ymin']),
  4859. (obj.options['xmax'], obj.options['ymin']),
  4860. (obj.options['xmax'], obj.options['ymax']),
  4861. (obj.options['xmin'], obj.options['ymax'])]
  4862. )
  4863. if Point(pos).within(poly_obj):
  4864. if obj.isHovering is False:
  4865. obj.isHovering = True
  4866. obj.notHovering = True
  4867. # create the selection box around the selected object
  4868. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4869. else:
  4870. if obj.notHovering is True:
  4871. obj.notHovering = False
  4872. obj.isHovering = False
  4873. self.delete_hover_shape()
  4874. except Exception:
  4875. # the Exception here will happen if we try to select on screen and we have an
  4876. # newly (and empty) just created Geometry or Excellon object that do not have the
  4877. # xmin, xmax, ymin, ymax options.
  4878. # In this case poly_obj creation (see above) will fail
  4879. pass
  4880. except Exception as e:
  4881. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4882. self.ui.position_label.setText("")
  4883. # self.ui.rel_position_label.setText("")
  4884. self.mouse = None
  4885. def on_mouse_click_release_over_plot(self, event):
  4886. """
  4887. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4888. and has been registered in ''self.__init__()''.
  4889. :param event: contains information about the event.
  4890. :return:
  4891. """
  4892. if self.is_legacy is False:
  4893. event_pos = event.pos
  4894. right_button = 2
  4895. else:
  4896. event_pos = (event.xdata, event.ydata)
  4897. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4898. right_button = 3
  4899. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4900. if self.grid_status():
  4901. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4902. else:
  4903. pos = (pos_canvas[0], pos_canvas[1])
  4904. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4905. # canvas menu
  4906. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4907. self.ui.popMenu.mouse_is_panning = False
  4908. self.cursor = QtGui.QCursor()
  4909. self.populate_cmenu_grids()
  4910. self.ui.popMenu.popup(self.cursor.pos())
  4911. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4912. # selection and then select a type of selection ("enclosing" or "touching")
  4913. if event.button == 1: # left click
  4914. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4915. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4916. if modifiers == QtCore.Qt.ShiftModifier:
  4917. # do not auto open the Project Tab
  4918. self.click_noproject = True
  4919. self.clipboard.setText(
  4920. self.defaults["global_point_clipboard_format"] %
  4921. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4922. )
  4923. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4924. return
  4925. if self.doubleclick is True:
  4926. self.doubleclick = False
  4927. if self.collection.get_selected():
  4928. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4929. if self.ui.splitter.sizes()[0] == 0:
  4930. self.ui.splitter.setSizes([1, 1])
  4931. try:
  4932. # delete the selection shape(S) as it may be in the way
  4933. self.delete_selection_shape()
  4934. self.delete_hover_shape()
  4935. except Exception as e:
  4936. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4937. return
  4938. else:
  4939. # WORKAROUND for LEGACY MODE
  4940. if self.is_legacy is True:
  4941. # if there is no move on canvas then we have no dragging selection
  4942. if self.dx == 0 or self.dy == 0:
  4943. self.selection_type = None
  4944. if self.selection_type is not None:
  4945. try:
  4946. self.selection_area_handler(self.pos, pos, self.selection_type)
  4947. self.selection_type = None
  4948. except Exception as e:
  4949. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4950. return
  4951. else:
  4952. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4953. if key_modifier == QtCore.Qt.ShiftModifier:
  4954. mod_key = 'Shift'
  4955. elif key_modifier == QtCore.Qt.ControlModifier:
  4956. mod_key = 'Control'
  4957. else:
  4958. mod_key = None
  4959. try:
  4960. if self.command_active is None:
  4961. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4962. # deselect, and if it's not selected then it will be selected
  4963. # If there is no active command (self.command_active is None) then we check if we clicked
  4964. # on a object by checking the bounding limits against mouse click position
  4965. if mod_key == self.defaults["global_mselect_key"]:
  4966. self.select_objects(key='multisel')
  4967. else:
  4968. # If there is no active command (self.command_active is None) then we check if
  4969. # we clicked on a object by checking the bounding limits against mouse click position
  4970. self.select_objects()
  4971. self.delete_hover_shape()
  4972. except Exception as e:
  4973. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4974. return
  4975. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4976. """
  4977. :param start_pos: mouse position when the selection LMB click was done
  4978. :param end_pos: mouse position when the left mouse button is released
  4979. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4980. :return:
  4981. """
  4982. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4983. # delete previous selection shape
  4984. self.delete_selection_shape()
  4985. # make all objects inactive
  4986. self.collection.set_all_inactive()
  4987. for obj in self.collection.get_list():
  4988. try:
  4989. # select the object(s) only if it is enabled (plotted)
  4990. if obj.options['plot']:
  4991. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4992. (obj.options['xmax'], obj.options['ymin']),
  4993. (obj.options['xmax'], obj.options['ymax']),
  4994. (obj.options['xmin'], obj.options['ymax'])])
  4995. if sel_type is True:
  4996. if poly_obj.within(poly_selection):
  4997. # create the selection box around the selected object
  4998. if self.defaults['global_selection_shape'] is True:
  4999. self.draw_selection_shape(obj)
  5000. self.collection.set_active(obj.options['name'])
  5001. else:
  5002. if poly_selection.intersects(poly_obj):
  5003. # create the selection box around the selected object
  5004. if self.defaults['global_selection_shape'] is True:
  5005. self.draw_selection_shape(obj)
  5006. self.collection.set_active(obj.options['name'])
  5007. obj.selection_shape_drawn = True
  5008. except Exception as e:
  5009. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5010. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5011. # In this case poly_obj creation (see above) will fail
  5012. log.debug("App.selection_area_handler() --> %s" % str(e))
  5013. def select_objects(self, key=None):
  5014. """
  5015. Will select objects clicked on canvas
  5016. :param key: for future use in cumulative selection
  5017. :return:
  5018. """
  5019. # list where we store the overlapped objects under our mouse left click position
  5020. if key is None:
  5021. self.objects_under_the_click_list = []
  5022. # Populate the list with the overlapped objects on the click position
  5023. curr_x, curr_y = self.pos
  5024. for obj in self.all_objects_list:
  5025. # ScriptObject and DocumentObject objects can't be selected
  5026. if obj.kind == 'script' or obj.kind == 'document':
  5027. continue
  5028. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5029. continue
  5030. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5031. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5032. if obj.options['name'] not in self.objects_under_the_click_list:
  5033. if obj.options['plot']:
  5034. # add objects to the objects_under_the_click list only if the object is plotted
  5035. # (active and not disabled)
  5036. self.objects_under_the_click_list.append(obj.options['name'])
  5037. try:
  5038. if self.objects_under_the_click_list:
  5039. curr_sel_obj = self.collection.get_active()
  5040. # case when there is only an object under the click and we toggle it
  5041. if len(self.objects_under_the_click_list) == 1:
  5042. if curr_sel_obj is None:
  5043. self.collection.set_active(self.objects_under_the_click_list[0])
  5044. curr_sel_obj = self.collection.get_active()
  5045. # create the selection box around the selected object
  5046. if self.defaults['global_selection_shape'] is True:
  5047. self.draw_selection_shape(curr_sel_obj)
  5048. curr_sel_obj.selection_shape_drawn = True
  5049. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5050. self.collection.on_objects_selection(False)
  5051. self.delete_selection_shape()
  5052. curr_sel_obj.selection_shape_drawn = False
  5053. self.collection.set_active(self.objects_under_the_click_list[0])
  5054. curr_sel_obj = self.collection.get_active()
  5055. # create the selection box around the selected object
  5056. if self.defaults['global_selection_shape'] is True:
  5057. self.draw_selection_shape(curr_sel_obj)
  5058. curr_sel_obj.selection_shape_drawn = True
  5059. self.selected_message(curr_sel_obj=curr_sel_obj)
  5060. elif curr_sel_obj.selection_shape_drawn is False:
  5061. if self.defaults['global_selection_shape'] is True:
  5062. self.draw_selection_shape(curr_sel_obj)
  5063. curr_sel_obj.selection_shape_drawn = True
  5064. else:
  5065. self.collection.on_objects_selection(False)
  5066. self.delete_selection_shape()
  5067. if self.call_source != 'app':
  5068. self.call_source = 'app'
  5069. self.selected_message(curr_sel_obj=curr_sel_obj)
  5070. else:
  5071. # If there is no selected object
  5072. # make active the first element of the overlapped objects list
  5073. if self.collection.get_active() is None:
  5074. self.collection.set_active(self.objects_under_the_click_list[0])
  5075. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5076. name_sel_obj = self.collection.get_active().options['name']
  5077. # In case that there is a selected object but it is not in the overlapped object list
  5078. # make that object inactive and activate the first element in the overlapped object list
  5079. if name_sel_obj not in self.objects_under_the_click_list:
  5080. self.collection.set_inactive(name_sel_obj)
  5081. name_sel_obj = self.objects_under_the_click_list[0]
  5082. self.collection.set_active(name_sel_obj)
  5083. else:
  5084. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5085. self.collection.set_all_inactive()
  5086. self.collection.set_active(
  5087. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5088. curr_sel_obj = self.collection.get_active()
  5089. # delete the possible selection box around a possible selected object
  5090. self.delete_selection_shape()
  5091. curr_sel_obj.selection_shape_drawn = False
  5092. # create the selection box around the selected object
  5093. if self.defaults['global_selection_shape'] is True:
  5094. self.draw_selection_shape(curr_sel_obj)
  5095. curr_sel_obj.selection_shape_drawn = True
  5096. self.selected_message(curr_sel_obj=curr_sel_obj)
  5097. else:
  5098. # deselect everything
  5099. self.collection.on_objects_selection(False)
  5100. # delete the possible selection box around a possible selected object
  5101. self.delete_selection_shape()
  5102. for o in self.collection.get_list():
  5103. o.selection_shape_drawn = False
  5104. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5105. # only when working on App
  5106. if self.call_source == 'app':
  5107. if self.click_noproject is False:
  5108. # if the Tool Tab is in focus don't change focus to Project Tab
  5109. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5110. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5111. else:
  5112. # restore auto open the Project Tab
  5113. self.click_noproject = False
  5114. # delete any text in the status bar, implicitly the last object name that was selected
  5115. # self.inform.emit("")
  5116. else:
  5117. self.call_source = 'app'
  5118. except Exception as e:
  5119. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5120. def selected_message(self, curr_sel_obj):
  5121. if curr_sel_obj:
  5122. if curr_sel_obj.kind == 'gerber':
  5123. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5124. color='green',
  5125. name=str(curr_sel_obj.options['name']),
  5126. tx=_("selected"))
  5127. )
  5128. elif curr_sel_obj.kind == 'excellon':
  5129. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5130. color='brown',
  5131. name=str(curr_sel_obj.options['name']),
  5132. tx=_("selected"))
  5133. )
  5134. elif curr_sel_obj.kind == 'cncjob':
  5135. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5136. color='blue',
  5137. name=str(curr_sel_obj.options['name']),
  5138. tx=_("selected"))
  5139. )
  5140. elif curr_sel_obj.kind == 'geometry':
  5141. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5142. color='red',
  5143. name=str(curr_sel_obj.options['name']),
  5144. tx=_("selected"))
  5145. )
  5146. def delete_hover_shape(self):
  5147. self.hover_shapes.clear()
  5148. self.hover_shapes.redraw()
  5149. def draw_hover_shape(self, sel_obj, color=None):
  5150. """
  5151. :param sel_obj: The object for which the hover shape must be drawn
  5152. :param color: The color of the hover shape
  5153. :return: None
  5154. """
  5155. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5156. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5157. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5158. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5159. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5160. if self.defaults['units'].upper() == 'MM':
  5161. hover_rect = hover_rect.buffer(-0.1)
  5162. hover_rect = hover_rect.buffer(0.2)
  5163. else:
  5164. hover_rect = hover_rect.buffer(-0.00393)
  5165. hover_rect = hover_rect.buffer(0.00787)
  5166. # if color:
  5167. # face = Color(color)
  5168. # face.alpha = 0.2
  5169. # outline = Color(color, alpha=0.8)
  5170. # else:
  5171. # face = Color(self.defaults['global_sel_fill'])
  5172. # face.alpha = 0.2
  5173. # outline = self.defaults['global_sel_line']
  5174. if color:
  5175. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5176. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5177. else:
  5178. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5179. outline = self.defaults['global_sel_line']
  5180. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5181. if self.is_legacy is True:
  5182. self.hover_shapes.redraw()
  5183. def delete_selection_shape(self):
  5184. self.move_tool.sel_shapes.clear()
  5185. self.move_tool.sel_shapes.redraw()
  5186. def draw_selection_shape(self, sel_obj, color=None):
  5187. """
  5188. Will draw a selection shape around the selected object.
  5189. :param sel_obj: The object for which the selection shape must be drawn
  5190. :param color: The color for the selection shape.
  5191. :return: None
  5192. """
  5193. if sel_obj is None:
  5194. return
  5195. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5196. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5197. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5198. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5199. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5200. if self.defaults['units'].upper() == 'MM':
  5201. sel_rect = sel_rect.buffer(-0.1)
  5202. sel_rect = sel_rect.buffer(0.2)
  5203. else:
  5204. sel_rect = sel_rect.buffer(-0.00393)
  5205. sel_rect = sel_rect.buffer(0.00787)
  5206. if color:
  5207. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5208. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5209. else:
  5210. if self.is_legacy is False:
  5211. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5212. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5213. else:
  5214. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5215. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5216. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5217. color=outline,
  5218. face_color=face,
  5219. update=True,
  5220. layer=0,
  5221. tolerance=None))
  5222. if self.is_legacy is True:
  5223. self.move_tool.sel_shapes.redraw()
  5224. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5225. """
  5226. Will draw a selection shape when dragging mouse on canvas.
  5227. :param old_coords: Old coordinates
  5228. :param coords: New coordinates
  5229. :param kwargs: Keyword arguments
  5230. :return:
  5231. """
  5232. if 'color' in kwargs:
  5233. color = kwargs['color']
  5234. else:
  5235. color = self.defaults['global_sel_line']
  5236. if 'face_color' in kwargs:
  5237. face_color = kwargs['face_color']
  5238. else:
  5239. face_color = self.defaults['global_sel_fill']
  5240. if 'face_alpha' in kwargs:
  5241. face_alpha = kwargs['face_alpha']
  5242. else:
  5243. face_alpha = 0.3
  5244. x0, y0 = old_coords
  5245. x1, y1 = coords
  5246. pt1 = (x0, y0)
  5247. pt2 = (x1, y0)
  5248. pt3 = (x1, y1)
  5249. pt4 = (x0, y1)
  5250. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5251. # color_t = Color(face_color)
  5252. # color_t.alpha = face_alpha
  5253. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5254. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5255. layer=0, tolerance=None)
  5256. if self.is_legacy is True:
  5257. self.move_tool.sel_shapes.redraw()
  5258. def on_file_new_click(self):
  5259. """
  5260. Callback for menu item File -> New.
  5261. Executed on clicking the Menu -> File -> New Project
  5262. :return:
  5263. """
  5264. if self.collection.get_list() and self.should_we_save:
  5265. msgbox = QtWidgets.QMessageBox()
  5266. # msgbox.setText("<B>Save changes ...</B>")
  5267. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5268. "Creating a New project will delete them.\n"
  5269. "Do you want to Save the project?"))
  5270. msgbox.setWindowTitle(_("Save changes"))
  5271. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5272. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5273. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5274. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5275. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5276. msgbox.setDefaultButton(bt_yes)
  5277. msgbox.exec_()
  5278. response = msgbox.clickedButton()
  5279. if response == bt_yes:
  5280. self.on_file_saveprojectas()
  5281. elif response == bt_cancel:
  5282. return
  5283. elif response == bt_no:
  5284. self.on_file_new()
  5285. else:
  5286. self.on_file_new()
  5287. self.inform.emit('[success] %s...' % _("New Project created"))
  5288. def on_file_new(self, cli=None):
  5289. """
  5290. Returns the application to its startup state. This method is thread-safe.
  5291. :param cli: Boolean. If True this method was run from command line
  5292. :return: None
  5293. """
  5294. self.defaults.report_usage("on_file_new")
  5295. # Remove everything from memory
  5296. App.log.debug("on_file_new()")
  5297. # close any editor that might be open
  5298. if self.call_source != 'app':
  5299. self.editor2object(cleanup=True)
  5300. # ## EDITOR section
  5301. self.geo_editor = FlatCAMGeoEditor(self)
  5302. self.exc_editor = FlatCAMExcEditor(self)
  5303. self.grb_editor = FlatCAMGrbEditor(self)
  5304. # Clear pool
  5305. self.clear_pool()
  5306. for obj in self.collection.get_list():
  5307. # delete shapes left drawn from mark shape_collections, if any
  5308. if isinstance(obj, GerberObject):
  5309. try:
  5310. for el in obj.mark_shapes:
  5311. obj.mark_shapes[el].clear(update=True)
  5312. obj.mark_shapes[el].enabled = False
  5313. del el
  5314. except AttributeError:
  5315. pass
  5316. # also delete annotation shapes, if any
  5317. elif isinstance(obj, CNCJobObject):
  5318. try:
  5319. obj.text_col.enabled = False
  5320. del obj.text_col
  5321. obj.annotation.clear(update=True)
  5322. del obj.annotation
  5323. except AttributeError:
  5324. pass
  5325. # delete the exclusion areas
  5326. self.exc_areas.clear_shapes()
  5327. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5328. self.shell.init_tcl()
  5329. # delete any selection shape on canvas
  5330. self.delete_selection_shape()
  5331. # delete all FlatCAM objects
  5332. self.collection.delete_all()
  5333. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5334. self.setup_component_editor()
  5335. # Clear project filename
  5336. self.project_filename = None
  5337. # Load the application defaults
  5338. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5339. # Re-fresh project options
  5340. self.on_options_app2project()
  5341. # Init FlatCAMTools
  5342. self.init_tools()
  5343. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5344. if cli is None:
  5345. # we need to go in reverse because once we remove a tab then the index changes
  5346. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5347. # and so on. Therefore the deletion should be done in reverse
  5348. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5349. for index in range(wdg_count, -1, -1):
  5350. try:
  5351. self.ui.plot_tab_area.closeTab(index)
  5352. except Exception as e:
  5353. log.debug("App.on_file_new() --> %s" % str(e))
  5354. # # And then add again the Plot Area
  5355. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5356. self.ui.plot_tab_area.protectTab(0)
  5357. # take the focus of the Notebook on Project Tab.
  5358. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5359. self.set_ui_title(name=_("New Project - Not saved"))
  5360. def obj_properties(self):
  5361. """
  5362. Will launch the object Properties Tool
  5363. :return:
  5364. """
  5365. self.defaults.report_usage("obj_properties()")
  5366. self.properties_tool.run(toggle=False)
  5367. def on_project_context_save(self):
  5368. """
  5369. Wrapper, will save the object function of it's type
  5370. :return:
  5371. """
  5372. obj = self.collection.get_active()
  5373. if type(obj) == GeometryObject:
  5374. self.on_file_exportdxf()
  5375. elif type(obj) == ExcellonObject:
  5376. self.on_file_saveexcellon()
  5377. elif type(obj) == CNCJobObject:
  5378. obj.on_exportgcode_button_click()
  5379. elif type(obj) == GerberObject:
  5380. self.on_file_savegerber()
  5381. elif type(obj) == ScriptObject:
  5382. self.on_file_savescript()
  5383. elif type(obj) == DocumentObject:
  5384. self.on_file_savedocument()
  5385. def obj_move(self):
  5386. """
  5387. Callback for the Move menu entry in various Context Menu's.
  5388. :return:
  5389. """
  5390. self.defaults.report_usage("obj_move()")
  5391. self.move_tool.run(toggle=False)
  5392. def on_fileopengerber(self, signal, name=None):
  5393. """
  5394. File menu callback for opening a Gerber.
  5395. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5396. :param name:
  5397. :return: None
  5398. """
  5399. self.defaults.report_usage("on_fileopengerber")
  5400. App.log.debug("on_fileopengerber()")
  5401. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5402. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5403. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5404. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5405. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5406. "*.mil);;" \
  5407. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5408. "Allegro Files (*.art);;" \
  5409. "Mentor Files (*.pho *.gdo);;" \
  5410. "All Files (*.*)"
  5411. if name is None:
  5412. try:
  5413. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5414. directory=self.get_last_folder(),
  5415. filter=_filter_)
  5416. except TypeError:
  5417. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5418. filenames = [str(filename) for filename in filenames]
  5419. else:
  5420. filenames = [name]
  5421. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5422. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5423. _("Opening Gerber file.")),
  5424. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5425. color=QtGui.QColor("gray"))
  5426. if len(filenames) == 0:
  5427. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5428. else:
  5429. for filename in filenames:
  5430. if filename != '':
  5431. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5432. def on_fileopenexcellon(self, signal, name=None):
  5433. """
  5434. File menu callback for opening an Excellon file.
  5435. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5436. :param name:
  5437. :return: None
  5438. """
  5439. self.defaults.report_usage("on_fileopenexcellon")
  5440. App.log.debug("on_fileopenexcellon()")
  5441. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5442. "All Files (*.*)"
  5443. if name is None:
  5444. try:
  5445. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5446. directory=self.get_last_folder(),
  5447. filter=_filter_)
  5448. except TypeError:
  5449. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5450. filenames = [str(filename) for filename in filenames]
  5451. else:
  5452. filenames = [str(name)]
  5453. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5454. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5455. _("Opening Excellon file.")),
  5456. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5457. color=QtGui.QColor("gray"))
  5458. if len(filenames) == 0:
  5459. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5460. else:
  5461. for filename in filenames:
  5462. if filename != '':
  5463. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5464. def on_fileopengcode(self, signal, name=None):
  5465. """
  5466. File menu call back for opening gcode.
  5467. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5468. :param name:
  5469. :return:
  5470. """
  5471. self.defaults.report_usage("on_fileopengcode")
  5472. App.log.debug("on_fileopengcode()")
  5473. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5474. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5475. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5476. "All Files (*.*)"
  5477. if name is None:
  5478. try:
  5479. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5480. directory=self.get_last_folder(),
  5481. filter=_filter_)
  5482. except TypeError:
  5483. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5484. filenames = [str(filename) for filename in filenames]
  5485. else:
  5486. filenames = [name]
  5487. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5488. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5489. _("Opening G-Code file.")),
  5490. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5491. color=QtGui.QColor("gray"))
  5492. if len(filenames) == 0:
  5493. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5494. else:
  5495. for filename in filenames:
  5496. if filename != '':
  5497. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5498. def on_file_openproject(self, signal):
  5499. """
  5500. File menu callback for opening a project.
  5501. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5502. :return: None
  5503. """
  5504. self.defaults.report_usage("on_file_openproject")
  5505. App.log.debug("on_file_openproject()")
  5506. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5507. try:
  5508. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5509. directory=self.get_last_folder(), filter=_filter_)
  5510. except TypeError:
  5511. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5512. # The Qt methods above will return a QString which can cause problems later.
  5513. # So far json.dump() will fail to serialize it.
  5514. # TODO: Improve the serialization methods and remove this fix.
  5515. filename = str(filename)
  5516. if filename == "":
  5517. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5518. else:
  5519. # self.worker_task.emit({'fcn': self.open_project,
  5520. # 'params': [filename]})
  5521. # The above was failing because open_project() is not
  5522. # thread safe. The new_project()
  5523. self.open_project(filename)
  5524. def on_fileopenhpgl2(self, signal, name=None):
  5525. """
  5526. File menu callback for opening a HPGL2.
  5527. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5528. :param name:
  5529. :return: None
  5530. """
  5531. self.defaults.report_usage("on_fileopenhpgl2")
  5532. App.log.debug("on_fileopenhpgl2()")
  5533. _filter_ = "HPGL2 Files (*.plt);;" \
  5534. "All Files (*.*)"
  5535. if name is None:
  5536. try:
  5537. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5538. directory=self.get_last_folder(),
  5539. filter=_filter_)
  5540. except TypeError:
  5541. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5542. filenames = [str(filename) for filename in filenames]
  5543. else:
  5544. filenames = [name]
  5545. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5546. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5547. _("Opening HPGL2 file.")),
  5548. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5549. color=QtGui.QColor("gray"))
  5550. if len(filenames) == 0:
  5551. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5552. else:
  5553. for filename in filenames:
  5554. if filename != '':
  5555. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5556. def on_file_openconfig(self, signal):
  5557. """
  5558. File menu callback for opening a config file.
  5559. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5560. :return: None
  5561. """
  5562. self.defaults.report_usage("on_file_openconfig")
  5563. App.log.debug("on_file_openconfig()")
  5564. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5565. try:
  5566. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5567. directory=self.data_path, filter=_filter_)
  5568. except TypeError:
  5569. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5570. filter=_filter_)
  5571. if filename == "":
  5572. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5573. else:
  5574. self.open_config_file(filename)
  5575. def on_file_exportsvg(self):
  5576. """
  5577. Callback for menu item File->Export SVG.
  5578. :return: None
  5579. """
  5580. self.defaults.report_usage("on_file_exportsvg")
  5581. App.log.debug("on_file_exportsvg()")
  5582. obj = self.collection.get_active()
  5583. if obj is None:
  5584. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5585. msg = _("Please Select a Geometry object to export")
  5586. msgbox = QtWidgets.QMessageBox()
  5587. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5588. msgbox.setInformativeText(msg)
  5589. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5590. msgbox.setDefaultButton(bt_ok)
  5591. msgbox.exec_()
  5592. return
  5593. # Check for more compatible types and add as required
  5594. if (not isinstance(obj, GeometryObject)
  5595. and not isinstance(obj, GerberObject)
  5596. and not isinstance(obj, CNCJobObject)
  5597. and not isinstance(obj, ExcellonObject)):
  5598. msg = '[ERROR_NOTCL] %s' % \
  5599. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5600. msgbox = QtWidgets.QMessageBox()
  5601. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5602. msgbox.setInformativeText(msg)
  5603. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5604. msgbox.setDefaultButton(bt_ok)
  5605. msgbox.exec_()
  5606. return
  5607. name = obj.options["name"]
  5608. _filter = "SVG File (*.svg);;All Files (*.*)"
  5609. try:
  5610. filename, _f = FCFileSaveDialog.get_saved_filename(
  5611. caption=_("Export SVG"),
  5612. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5613. filter=_filter)
  5614. except TypeError:
  5615. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5616. filename = str(filename)
  5617. if filename == "":
  5618. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5619. return
  5620. else:
  5621. self.export_svg(name, filename)
  5622. if self.defaults["global_open_style"] is False:
  5623. self.file_opened.emit("SVG", filename)
  5624. self.file_saved.emit("SVG", filename)
  5625. def on_file_exportpng(self):
  5626. self.defaults.report_usage("on_file_exportpng")
  5627. App.log.debug("on_file_exportpng()")
  5628. self.date = str(datetime.today()).rpartition('.')[0]
  5629. self.date = ''.join(c for c in self.date if c not in ':-')
  5630. self.date = self.date.replace(' ', '_')
  5631. if self.is_legacy is False:
  5632. image = _screenshot()
  5633. data = np.asarray(image)
  5634. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5635. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5636. return
  5637. filter_ = "PNG File (*.png);;All Files (*.*)"
  5638. try:
  5639. filename, _f = FCFileSaveDialog.get_saved_filename(
  5640. caption=_("Export PNG Image"),
  5641. directory=self.get_last_save_folder() + '/png_' + self.date,
  5642. filter=filter_)
  5643. except TypeError:
  5644. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5645. filename = str(filename)
  5646. if filename == "":
  5647. self.inform.emit(_("Cancelled."))
  5648. return
  5649. else:
  5650. if self.is_legacy is False:
  5651. write_png(filename, data)
  5652. else:
  5653. self.plotcanvas.figure.savefig(filename)
  5654. if self.defaults["global_open_style"] is False:
  5655. self.file_opened.emit("png", filename)
  5656. self.file_saved.emit("png", filename)
  5657. def on_file_savegerber(self):
  5658. """
  5659. Callback for menu item in Project context menu.
  5660. :return: None
  5661. """
  5662. self.defaults.report_usage("on_file_savegerber")
  5663. App.log.debug("on_file_savegerber()")
  5664. obj = self.collection.get_active()
  5665. if obj is None:
  5666. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5667. return
  5668. # Check for more compatible types and add as required
  5669. if not isinstance(obj, GerberObject):
  5670. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5671. return
  5672. name = self.collection.get_active().options["name"]
  5673. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5674. try:
  5675. filename, _f = FCFileSaveDialog.get_saved_filename(
  5676. caption="Save Gerber source file",
  5677. directory=self.get_last_save_folder() + '/' + name,
  5678. filter=_filter)
  5679. except TypeError:
  5680. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5681. filename = str(filename)
  5682. if filename == "":
  5683. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5684. return
  5685. else:
  5686. self.save_source_file(name, filename)
  5687. if self.defaults["global_open_style"] is False:
  5688. self.file_opened.emit("Gerber", filename)
  5689. self.file_saved.emit("Gerber", filename)
  5690. def on_file_savescript(self):
  5691. """
  5692. Callback for menu item in Project context menu.
  5693. :return: None
  5694. """
  5695. self.defaults.report_usage("on_file_savescript")
  5696. App.log.debug("on_file_savescript()")
  5697. obj = self.collection.get_active()
  5698. if obj is None:
  5699. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5700. return
  5701. # Check for more compatible types and add as required
  5702. if not isinstance(obj, ScriptObject):
  5703. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5704. return
  5705. name = self.collection.get_active().options["name"]
  5706. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5707. try:
  5708. filename, _f = FCFileSaveDialog.get_saved_filename(
  5709. caption="Save Script source file",
  5710. directory=self.get_last_save_folder() + '/' + name,
  5711. filter=_filter)
  5712. except TypeError:
  5713. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5714. filename = str(filename)
  5715. if filename == "":
  5716. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5717. return
  5718. else:
  5719. self.save_source_file(name, filename)
  5720. if self.defaults["global_open_style"] is False:
  5721. self.file_opened.emit("Script", filename)
  5722. self.file_saved.emit("Script", filename)
  5723. def on_file_savedocument(self):
  5724. """
  5725. Callback for menu item in Project context menu.
  5726. :return: None
  5727. """
  5728. self.defaults.report_usage("on_file_savedocument")
  5729. App.log.debug("on_file_savedocument()")
  5730. obj = self.collection.get_active()
  5731. if obj is None:
  5732. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5733. return
  5734. # Check for more compatible types and add as required
  5735. if not isinstance(obj, ScriptObject):
  5736. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5737. return
  5738. name = self.collection.get_active().options["name"]
  5739. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5740. try:
  5741. filename, _f = FCFileSaveDialog.get_saved_filename(
  5742. caption="Save Document source file",
  5743. directory=self.get_last_save_folder() + '/' + name,
  5744. filter=_filter)
  5745. except TypeError:
  5746. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5747. filename = str(filename)
  5748. if filename == "":
  5749. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5750. return
  5751. else:
  5752. self.save_source_file(name, filename)
  5753. if self.defaults["global_open_style"] is False:
  5754. self.file_opened.emit("Document", filename)
  5755. self.file_saved.emit("Document", filename)
  5756. def on_file_saveexcellon(self):
  5757. """
  5758. Callback for menu item in project context menu.
  5759. :return: None
  5760. """
  5761. self.defaults.report_usage("on_file_saveexcellon")
  5762. App.log.debug("on_file_saveexcellon()")
  5763. obj = self.collection.get_active()
  5764. if obj is None:
  5765. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5766. return
  5767. # Check for more compatible types and add as required
  5768. if not isinstance(obj, ExcellonObject):
  5769. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5770. return
  5771. name = self.collection.get_active().options["name"]
  5772. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5773. try:
  5774. filename, _f = FCFileSaveDialog.get_saved_filename(
  5775. caption=_("Save Excellon source file"),
  5776. directory=self.get_last_save_folder() + '/' + name,
  5777. filter=_filter)
  5778. except TypeError:
  5779. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5780. filename = str(filename)
  5781. if filename == "":
  5782. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5783. return
  5784. else:
  5785. self.save_source_file(name, filename)
  5786. if self.defaults["global_open_style"] is False:
  5787. self.file_opened.emit("Excellon", filename)
  5788. self.file_saved.emit("Excellon", filename)
  5789. def on_file_exportexcellon(self):
  5790. """
  5791. Callback for menu item File->Export->Excellon.
  5792. :return: None
  5793. """
  5794. self.defaults.report_usage("on_file_exportexcellon")
  5795. App.log.debug("on_file_exportexcellon()")
  5796. obj = self.collection.get_active()
  5797. if obj is None:
  5798. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5799. return
  5800. # Check for more compatible types and add as required
  5801. if not isinstance(obj, ExcellonObject):
  5802. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5803. return
  5804. name = self.collection.get_active().options["name"]
  5805. _filter = self.defaults["excellon_save_filters"]
  5806. try:
  5807. filename, _f = FCFileSaveDialog.get_saved_filename(
  5808. caption=_("Export Excellon"),
  5809. directory=self.get_last_save_folder() + '/' + name,
  5810. filter=_filter)
  5811. except TypeError:
  5812. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5813. filename = str(filename)
  5814. if filename == "":
  5815. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5816. return
  5817. else:
  5818. used_extension = filename.rpartition('.')[2]
  5819. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5820. self.export_excellon(name, filename)
  5821. if self.defaults["global_open_style"] is False:
  5822. self.file_opened.emit("Excellon", filename)
  5823. self.file_saved.emit("Excellon", filename)
  5824. def on_file_exportgerber(self):
  5825. """
  5826. Callback for menu item File->Export->Gerber.
  5827. :return: None
  5828. """
  5829. self.defaults.report_usage("on_file_exportgerber")
  5830. App.log.debug("on_file_exportgerber()")
  5831. obj = self.collection.get_active()
  5832. if obj is None:
  5833. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5834. return
  5835. # Check for more compatible types and add as required
  5836. if not isinstance(obj, GerberObject):
  5837. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5838. return
  5839. name = self.collection.get_active().options["name"]
  5840. _filter_ = self.defaults['gerber_save_filters']
  5841. try:
  5842. filename, _f = FCFileSaveDialog.get_saved_filename(
  5843. caption=_("Export Gerber"),
  5844. directory=self.get_last_save_folder() + '/' + name,
  5845. filter=_filter_)
  5846. except TypeError:
  5847. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5848. filename = str(filename)
  5849. if filename == "":
  5850. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5851. return
  5852. else:
  5853. used_extension = filename.rpartition('.')[2]
  5854. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5855. self.export_gerber(name, filename)
  5856. if self.defaults["global_open_style"] is False:
  5857. self.file_opened.emit("Gerber", filename)
  5858. self.file_saved.emit("Gerber", filename)
  5859. def on_file_exportdxf(self):
  5860. """
  5861. Callback for menu item File->Export DXF.
  5862. :return: None
  5863. """
  5864. self.defaults.report_usage("on_file_exportdxf")
  5865. App.log.debug("on_file_exportdxf()")
  5866. obj = self.collection.get_active()
  5867. if obj is None:
  5868. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5869. msg = _("Please Select a Geometry object to export")
  5870. msgbox = QtWidgets.QMessageBox()
  5871. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5872. msgbox.setInformativeText(msg)
  5873. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5874. msgbox.setDefaultButton(bt_ok)
  5875. msgbox.exec_()
  5876. return
  5877. # Check for more compatible types and add as required
  5878. if not isinstance(obj, GeometryObject):
  5879. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5880. msgbox = QtWidgets.QMessageBox()
  5881. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5882. msgbox.setInformativeText(msg)
  5883. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5884. msgbox.setDefaultButton(bt_ok)
  5885. msgbox.exec_()
  5886. return
  5887. name = self.collection.get_active().options["name"]
  5888. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5889. try:
  5890. filename, _f = FCFileSaveDialog.get_saved_filename(
  5891. caption=_("Export DXF"),
  5892. directory=self.get_last_save_folder() + '/' + name,
  5893. filter=_filter_)
  5894. except TypeError:
  5895. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5896. filename = str(filename)
  5897. if filename == "":
  5898. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5899. return
  5900. else:
  5901. self.export_dxf(name, filename)
  5902. if self.defaults["global_open_style"] is False:
  5903. self.file_opened.emit("DXF", filename)
  5904. self.file_saved.emit("DXF", filename)
  5905. def on_file_importsvg(self, type_of_obj):
  5906. """
  5907. Callback for menu item File->Import SVG.
  5908. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5909. :type type_of_obj: str
  5910. :return: None
  5911. """
  5912. self.defaults.report_usage("on_file_importsvg")
  5913. App.log.debug("on_file_importsvg()")
  5914. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5915. try:
  5916. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5917. directory=self.get_last_folder(), filter=_filter_)
  5918. except TypeError:
  5919. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5920. filter=_filter_)
  5921. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5922. type_of_obj = "geometry"
  5923. filenames = [str(filename) for filename in filenames]
  5924. if len(filenames) == 0:
  5925. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5926. else:
  5927. for filename in filenames:
  5928. if filename != '':
  5929. self.worker_task.emit({'fcn': self.import_svg,
  5930. 'params': [filename, type_of_obj]})
  5931. def on_file_importdxf(self, type_of_obj):
  5932. """
  5933. Callback for menu item File->Import DXF.
  5934. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5935. :type type_of_obj: str
  5936. :return: None
  5937. """
  5938. self.defaults.report_usage("on_file_importdxf")
  5939. App.log.debug("on_file_importdxf()")
  5940. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5941. try:
  5942. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5943. directory=self.get_last_folder(),
  5944. filter=_filter_)
  5945. except TypeError:
  5946. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5947. filter=_filter_)
  5948. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5949. type_of_obj = "geometry"
  5950. filenames = [str(filename) for filename in filenames]
  5951. if len(filenames) == 0:
  5952. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5953. else:
  5954. for filename in filenames:
  5955. if filename != '':
  5956. self.worker_task.emit({'fcn': self.import_dxf,
  5957. 'params': [filename, type_of_obj]})
  5958. # ###############################################################################################################
  5959. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5960. # ###############################################################################################################
  5961. def init_code_editor(self, name):
  5962. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5963. # add the tab if it was closed
  5964. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5965. self.text_editor_tab.setObjectName('text_editor_tab')
  5966. # delete the absolute and relative position and messages in the infobar
  5967. self.ui.position_label.setText("")
  5968. # self.ui.rel_position_label.setText("")
  5969. # first clear previous text in text editor (if any)
  5970. self.text_editor_tab.code_editor.clear()
  5971. self.text_editor_tab.code_editor.setReadOnly(False)
  5972. self.toggle_codeeditor = True
  5973. self.text_editor_tab.code_editor.completer_enable = False
  5974. self.text_editor_tab.buttonRun.hide()
  5975. # make sure to keep a reference to the code editor
  5976. self.reference_code_editor = self.text_editor_tab.code_editor
  5977. # Switch plot_area to CNCJob tab
  5978. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5979. def on_view_source(self):
  5980. """
  5981. Called when the user wants to see the source file of the selected object
  5982. :return:
  5983. """
  5984. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5985. self.proc_container.view.set_busy(_("Loading..."))
  5986. try:
  5987. obj = self.collection.get_active()
  5988. except Exception as e:
  5989. log.debug("App.on_view_source() --> %s" % str(e))
  5990. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5991. return 'fail'
  5992. if obj is None:
  5993. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5994. return 'fail'
  5995. flt = "All Files (*.*)"
  5996. if obj.kind == 'gerber':
  5997. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5998. elif obj.kind == 'excellon':
  5999. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6000. elif obj.kind == 'cncjob':
  6001. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6002. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6003. # add the tab if it was closed
  6004. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6005. self.source_editor_tab.setObjectName('source_editor_tab')
  6006. # delete the absolute and relative position and messages in the infobar
  6007. self.ui.position_label.setText("")
  6008. # self.ui.rel_position_label.setText("")
  6009. # first clear previous text in text editor (if any)
  6010. self.source_editor_tab.code_editor.clear()
  6011. self.source_editor_tab.code_editor.setReadOnly(False)
  6012. self.source_editor_tab.code_editor.completer_enable = False
  6013. self.source_editor_tab.buttonRun.hide()
  6014. # Switch plot_area to CNCJob tab
  6015. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6016. try:
  6017. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6018. except TypeError:
  6019. pass
  6020. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6021. try:
  6022. self.source_editor_tab.buttonSave.clicked.disconnect()
  6023. except TypeError:
  6024. pass
  6025. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6026. # then append the text from GCode to the text editor
  6027. if obj.kind == 'cncjob':
  6028. try:
  6029. file = obj.export_gcode(
  6030. preamble=self.defaults["cncjob_prepend"],
  6031. postamble=self.defaults["cncjob_append"],
  6032. to_file=True)
  6033. if file == 'fail':
  6034. return 'fail'
  6035. except AttributeError:
  6036. self.inform.emit('[WARNING_NOTCL] %s' %
  6037. _("There is no selected object for which to see it's source file code."))
  6038. return 'fail'
  6039. else:
  6040. try:
  6041. file = StringIO(obj.source_file)
  6042. except (AttributeError, TypeError):
  6043. self.inform.emit('[WARNING_NOTCL] %s' %
  6044. _("There is no selected object for which to see it's source file code."))
  6045. return 'fail'
  6046. self.source_editor_tab.t_frame.hide()
  6047. try:
  6048. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6049. # for line in file:
  6050. # QtWidgets.QApplication.processEvents()
  6051. # proc_line = str(line).strip('\n')
  6052. # self.source_editor_tab.code_editor.append(proc_line)
  6053. except Exception as e:
  6054. log.debug('App.on_view_source() -->%s' % str(e))
  6055. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6056. return
  6057. self.source_editor_tab.handleTextChanged()
  6058. self.source_editor_tab.t_frame.show()
  6059. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6060. self.proc_container.view.set_idle()
  6061. # self.ui.show()
  6062. def on_toggle_code_editor(self):
  6063. self.defaults.report_usage("on_toggle_code_editor()")
  6064. if self.toggle_codeeditor is False:
  6065. self.init_code_editor(name=_("Code Editor"))
  6066. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6067. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6068. self.text_editor_tab.buttonSave.clicked.disconnect()
  6069. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6070. else:
  6071. for idx in range(self.ui.plot_tab_area.count()):
  6072. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6073. self.ui.plot_tab_area.closeTab(idx)
  6074. break
  6075. self.toggle_codeeditor = False
  6076. def on_code_editor_close(self):
  6077. self.toggle_codeeditor = False
  6078. def goto_text_line(self):
  6079. """
  6080. Will scroll a text to the specified text line.
  6081. :return: None
  6082. """
  6083. dia_box = Dialog_box(title=_("Go to Line ..."),
  6084. label=_("Line:"),
  6085. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6086. initial_text='')
  6087. try:
  6088. line = int(dia_box.location) - 1
  6089. except (ValueError, TypeError):
  6090. line = 0
  6091. if dia_box.ok:
  6092. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6093. # at the top of the window
  6094. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6095. # get the document() of the TextEditor
  6096. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6097. # create a Text Cursor based on the searched line
  6098. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6099. # set cursor of the code editor with the cursor at the searcehd line
  6100. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6101. def on_filenewscript(self, silent=False):
  6102. """
  6103. Will create a new script file and open it in the Code Editor
  6104. :param silent: if True will not display status messages
  6105. :return: None
  6106. """
  6107. if silent is False:
  6108. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6109. # delete the absolute and relative position and messages in the infobar
  6110. self.ui.position_label.setText("")
  6111. # self.ui.rel_position_label.setText("")
  6112. self.app_obj.new_script_object()
  6113. # script_text = script_obj.source_file
  6114. #
  6115. # self.proc_container.view.set_busy(_("Loading..."))
  6116. # script_obj.script_editor_tab.t_frame.hide()
  6117. #
  6118. # script_obj.script_editor_tab.t_frame.show()
  6119. # self.proc_container.view.set_idle()
  6120. def on_fileopenscript(self, name=None, silent=False):
  6121. """
  6122. Will open a Tcl script file into the Code Editor
  6123. :param silent: if True will not display status messages
  6124. :param name: name of a Tcl script file to open
  6125. :return: None
  6126. """
  6127. self.defaults.report_usage("on_fileopenscript")
  6128. App.log.debug("on_fileopenscript()")
  6129. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6130. "All Files (*.*)"
  6131. if name:
  6132. filenames = [name]
  6133. else:
  6134. try:
  6135. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6136. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6137. except TypeError:
  6138. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6139. if len(filenames) == 0:
  6140. if silent is False:
  6141. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6142. else:
  6143. for filename in filenames:
  6144. if filename != '':
  6145. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6146. def on_fileopenscript_example(self, name=None, silent=False):
  6147. """
  6148. Will open a Tcl script file into the Code Editor
  6149. :param silent: if True will not display status messages
  6150. :param name: name of a Tcl script file to open
  6151. :return:
  6152. """
  6153. self.defaults.report_usage("on_fileopenscript_example")
  6154. log.debug("on_fileopenscript_example()")
  6155. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6156. "All Files (*.*)"
  6157. # test if the app was frozen and choose the path for the configuration file
  6158. if getattr(sys, "frozen", False) is True:
  6159. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6160. else:
  6161. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6162. if name:
  6163. filenames = [name]
  6164. else:
  6165. try:
  6166. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6167. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6168. except TypeError:
  6169. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6170. if len(filenames) == 0:
  6171. if silent is False:
  6172. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6173. else:
  6174. for filename in filenames:
  6175. if filename != '':
  6176. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6177. def on_filerunscript(self, name=None, silent=False):
  6178. """
  6179. File menu callback for loading and running a TCL script.
  6180. :param silent: if True will not display status messages
  6181. :param name: name of a Tcl script file to be run by FlatCAM
  6182. :return: None
  6183. """
  6184. self.defaults.report_usage("on_filerunscript")
  6185. App.log.debug("on_file_runscript()")
  6186. if name:
  6187. filename = name
  6188. if self.cmd_line_headless != 1:
  6189. self.splash.showMessage('%s: %ssec\n%s' %
  6190. (_("Canvas initialization started.\n"
  6191. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6192. _("Executing ScriptObject file.")
  6193. ),
  6194. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6195. color=QtGui.QColor("gray"))
  6196. else:
  6197. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6198. "All Files (*.*)"
  6199. try:
  6200. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6201. directory=self.get_last_folder(), filter=_filter_)
  6202. except TypeError:
  6203. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6204. # The Qt methods above will return a QString which can cause problems later.
  6205. # So far json.dump() will fail to serialize it.
  6206. filename = str(filename)
  6207. if filename == "":
  6208. if silent is False:
  6209. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6210. else:
  6211. if self.cmd_line_headless != 1:
  6212. if self.ui.shell_dock.isHidden():
  6213. self.ui.shell_dock.show()
  6214. try:
  6215. with open(filename, "r") as tcl_script:
  6216. cmd_line_shellfile_content = tcl_script.read()
  6217. if self.cmd_line_headless != 1:
  6218. self.shell.exec_command(cmd_line_shellfile_content)
  6219. else:
  6220. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6221. if silent is False:
  6222. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6223. except Exception as e:
  6224. log.debug("App.on_filerunscript() -> %s" % str(e))
  6225. sys.exit(2)
  6226. def on_file_saveproject(self, silent=False):
  6227. """
  6228. Callback for menu item File->Save Project. Saves the project to
  6229. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6230. if set to None. The project is saved by calling ``self.save_project()``.
  6231. :param silent: if True will not display status messages
  6232. :return: None
  6233. """
  6234. self.defaults.report_usage("on_file_saveproject")
  6235. if self.project_filename is None:
  6236. self.on_file_saveprojectas()
  6237. else:
  6238. self.worker_task.emit({'fcn': self.save_project,
  6239. 'params': [self.project_filename, silent]})
  6240. if self.defaults["global_open_style"] is False:
  6241. self.file_opened.emit("project", self.project_filename)
  6242. self.file_saved.emit("project", self.project_filename)
  6243. self.set_ui_title(name=self.project_filename)
  6244. self.should_we_save = False
  6245. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6246. """
  6247. Callback for menu item File->Save Project As... Opens a file
  6248. chooser and saves the project to the given file via
  6249. ``self.save_project()``.
  6250. :param make_copy if to be create a copy of the project; boolean
  6251. :param use_thread: if to be run in a separate thread; boolean
  6252. :param quit_action: if to be followed by quiting the application; boolean
  6253. :return: None
  6254. """
  6255. self.defaults.report_usage("on_file_saveprojectas")
  6256. self.date = str(datetime.today()).rpartition('.')[0]
  6257. self.date = ''.join(c for c in self.date if c not in ':-')
  6258. self.date = self.date.replace(' ', '_')
  6259. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6260. try:
  6261. filename, _f = FCFileSaveDialog.get_saved_filename(
  6262. caption=_("Save Project As ..."),
  6263. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6264. proj=_("Project")),
  6265. filter=filter_
  6266. )
  6267. except TypeError:
  6268. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6269. filename = str(filename)
  6270. if filename == '':
  6271. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6272. return
  6273. if use_thread is True:
  6274. self.worker_task.emit({'fcn': self.save_project,
  6275. 'params': [filename, quit_action]})
  6276. else:
  6277. self.save_project(filename, quit_action)
  6278. # self.save_project(filename)
  6279. if self.defaults["global_open_style"] is False:
  6280. self.file_opened.emit("project", filename)
  6281. self.file_saved.emit("project", filename)
  6282. if not make_copy:
  6283. self.project_filename = filename
  6284. self.set_ui_title(name=self.project_filename)
  6285. self.should_we_save = False
  6286. def on_file_save_objects_pdf(self, use_thread=True):
  6287. self.date = str(datetime.today()).rpartition('.')[0]
  6288. self.date = ''.join(c for c in self.date if c not in ':-')
  6289. self.date = self.date.replace(' ', '_')
  6290. try:
  6291. obj_selection = self.collection.get_selected()
  6292. if len(obj_selection) == 1:
  6293. obj_name = str(obj_selection[0].options['name'])
  6294. else:
  6295. obj_name = _("FlatCAM objects print")
  6296. except AttributeError as err:
  6297. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6298. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6299. return
  6300. if not obj_selection:
  6301. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6302. return
  6303. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6304. try:
  6305. filename, _f = FCFileSaveDialog.get_saved_filename(
  6306. caption=_("Save Object as PDF ..."),
  6307. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6308. obj_name=obj_name,
  6309. date=self.date),
  6310. filter=filter_
  6311. )
  6312. except TypeError:
  6313. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6314. filename = str(filename)
  6315. if filename == '':
  6316. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6317. return
  6318. if use_thread is True:
  6319. self.proc_container.new(_("Printing PDF ... Please wait."))
  6320. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6321. else:
  6322. self.save_pdf(filename, obj_selection)
  6323. # self.save_project(filename)
  6324. if self.defaults["global_open_style"] is False:
  6325. self.file_opened.emit("pdf", filename)
  6326. self.file_saved.emit("pdf", filename)
  6327. def save_pdf(self, file_name, obj_selection):
  6328. p_size = self.defaults['global_workspaceT']
  6329. orientation = self.defaults['global_workspace_orientation']
  6330. color = 'black'
  6331. transparency_level = 1.0
  6332. self.pagesize = {}
  6333. self.pagesize.update(
  6334. {
  6335. 'Bounds': None,
  6336. 'A0': (841 * mm, 1189 * mm),
  6337. 'A1': (594 * mm, 841 * mm),
  6338. 'A2': (420 * mm, 594 * mm),
  6339. 'A3': (297 * mm, 420 * mm),
  6340. 'A4': (210 * mm, 297 * mm),
  6341. 'A5': (148 * mm, 210 * mm),
  6342. 'A6': (105 * mm, 148 * mm),
  6343. 'A7': (74 * mm, 105 * mm),
  6344. 'A8': (52 * mm, 74 * mm),
  6345. 'A9': (37 * mm, 52 * mm),
  6346. 'A10': (26 * mm, 37 * mm),
  6347. 'B0': (1000 * mm, 1414 * mm),
  6348. 'B1': (707 * mm, 1000 * mm),
  6349. 'B2': (500 * mm, 707 * mm),
  6350. 'B3': (353 * mm, 500 * mm),
  6351. 'B4': (250 * mm, 353 * mm),
  6352. 'B5': (176 * mm, 250 * mm),
  6353. 'B6': (125 * mm, 176 * mm),
  6354. 'B7': (88 * mm, 125 * mm),
  6355. 'B8': (62 * mm, 88 * mm),
  6356. 'B9': (44 * mm, 62 * mm),
  6357. 'B10': (31 * mm, 44 * mm),
  6358. 'C0': (917 * mm, 1297 * mm),
  6359. 'C1': (648 * mm, 917 * mm),
  6360. 'C2': (458 * mm, 648 * mm),
  6361. 'C3': (324 * mm, 458 * mm),
  6362. 'C4': (229 * mm, 324 * mm),
  6363. 'C5': (162 * mm, 229 * mm),
  6364. 'C6': (114 * mm, 162 * mm),
  6365. 'C7': (81 * mm, 114 * mm),
  6366. 'C8': (57 * mm, 81 * mm),
  6367. 'C9': (40 * mm, 57 * mm),
  6368. 'C10': (28 * mm, 40 * mm),
  6369. # American paper sizes
  6370. 'LETTER': (8.5 * inch, 11 * inch),
  6371. 'LEGAL': (8.5 * inch, 14 * inch),
  6372. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6373. # From https://en.wikipedia.org/wiki/Paper_size
  6374. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6375. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6376. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6377. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6378. 'LEDGER': (17 * inch, 11 * inch),
  6379. }
  6380. )
  6381. exported_svg = []
  6382. for obj in obj_selection:
  6383. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6384. scale_factor_x=None, scale_factor_y=None,
  6385. skew_factor_x=None, skew_factor_y=None,
  6386. mirror=None)
  6387. if obj.kind.lower() == 'gerber':
  6388. # color = self.defaults["gerber_plot_fill"][:-2]
  6389. color = obj.fill_color[:-2]
  6390. elif obj.kind.lower() == 'excellon':
  6391. color = '#C40000'
  6392. elif obj.kind.lower() == 'geometry':
  6393. color = self.defaults["global_draw_color"]
  6394. # Change the attributes of the exported SVG
  6395. # We don't need stroke-width
  6396. # We set opacity to maximum
  6397. # We set the colour to WHITE
  6398. root = ET.fromstring(svg_obj)
  6399. for child in root:
  6400. child.set('fill', str(color))
  6401. child.set('opacity', str(transparency_level))
  6402. child.set('stroke', str(color))
  6403. exported_svg.append(ET.tostring(root))
  6404. xmin = Inf
  6405. ymin = Inf
  6406. xmax = -Inf
  6407. ymax = -Inf
  6408. for obj in obj_selection:
  6409. try:
  6410. gxmin, gymin, gxmax, gymax = obj.bounds()
  6411. xmin = min([xmin, gxmin])
  6412. ymin = min([ymin, gymin])
  6413. xmax = max([xmax, gxmax])
  6414. ymax = max([ymax, gymax])
  6415. except Exception as e:
  6416. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6417. # Determine bounding area for svg export
  6418. bounds = [xmin, ymin, xmax, ymax]
  6419. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6420. # This contain the measure units
  6421. uom = obj_selection[0].units.lower()
  6422. # Define a boundary around SVG of about 1.0mm (~39mils)
  6423. if uom in "mm":
  6424. boundary = 1.0
  6425. else:
  6426. boundary = 0.0393701
  6427. # Convert everything to strings for use in the xml doc
  6428. svgwidth = str(size[0] + (2 * boundary))
  6429. svgheight = str(size[1] + (2 * boundary))
  6430. minx = str(bounds[0] - boundary)
  6431. miny = str(bounds[1] + boundary + size[1])
  6432. # Add a SVG Header and footer to the svg output from shapely
  6433. # The transform flips the Y Axis so that everything renders
  6434. # properly within svg apps such as inkscape
  6435. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6436. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6437. svg_header += 'width="' + svgwidth + uom + '" '
  6438. svg_header += 'height="' + svgheight + uom + '" '
  6439. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6440. svg_header += '>'
  6441. svg_header += '<g transform="scale(1,-1)">'
  6442. svg_footer = '</g> </svg>'
  6443. svg_elem = str(svg_header)
  6444. for svg_item in exported_svg:
  6445. svg_elem += str(svg_item)
  6446. svg_elem += str(svg_footer)
  6447. # Parse the xml through a xml parser just to add line feeds
  6448. # and to make it look more pretty for the output
  6449. doc = parse_xml_string(svg_elem)
  6450. doc_final = doc.toprettyxml()
  6451. try:
  6452. if self.defaults['units'].upper() == 'IN':
  6453. unit = inch
  6454. else:
  6455. unit = mm
  6456. doc_final = StringIO(doc_final)
  6457. drawing = svg2rlg(doc_final)
  6458. if p_size == 'Bounds':
  6459. renderPDF.drawToFile(drawing, file_name)
  6460. else:
  6461. if orientation == 'p':
  6462. page_size = portrait(self.pagesize[p_size])
  6463. else:
  6464. page_size = landscape(self.pagesize[p_size])
  6465. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6466. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6467. renderPDF.draw(drawing, my_canvas, 0, 0)
  6468. my_canvas.save()
  6469. except Exception as e:
  6470. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6471. return 'fail'
  6472. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6473. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6474. """
  6475. Exports a Geometry Object to an SVG file.
  6476. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6477. :param filename: Path to the SVG file to save to.
  6478. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6479. :return:
  6480. """
  6481. self.defaults.report_usage("export_svg()")
  6482. if filename is None:
  6483. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6484. is not None else self.defaults["global_last_folder"]
  6485. self.log.debug("export_svg()")
  6486. try:
  6487. obj = self.collection.get_by_name(str(obj_name))
  6488. except Exception:
  6489. # TODO: The return behavior has not been established... should raise exception?
  6490. return "Could not retrieve object: %s" % obj_name
  6491. with self.proc_container.new(_("Exporting SVG")) as proc:
  6492. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6493. # Determine bounding area for svg export
  6494. bounds = obj.bounds()
  6495. size = obj.size()
  6496. # Convert everything to strings for use in the xml doc
  6497. svgwidth = str(size[0])
  6498. svgheight = str(size[1])
  6499. minx = str(bounds[0])
  6500. miny = str(bounds[1] - size[1])
  6501. uom = obj.units.lower()
  6502. # Add a SVG Header and footer to the svg output from shapely
  6503. # The transform flips the Y Axis so that everything renders
  6504. # properly within svg apps such as inkscape
  6505. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6506. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6507. svg_header += 'width="' + svgwidth + uom + '" '
  6508. svg_header += 'height="' + svgheight + uom + '" '
  6509. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6510. svg_header += '<g transform="scale(1,-1)">'
  6511. svg_footer = '</g> </svg>'
  6512. svg_elem = svg_header + exported_svg + svg_footer
  6513. # Parse the xml through a xml parser just to add line feeds
  6514. # and to make it look more pretty for the output
  6515. svgcode = parse_xml_string(svg_elem)
  6516. svgcode = svgcode.toprettyxml()
  6517. try:
  6518. with open(filename, 'w') as fp:
  6519. fp.write(svgcode)
  6520. except PermissionError:
  6521. self.inform.emit('[WARNING] %s' %
  6522. _("Permission denied, saving not possible.\n"
  6523. "Most likely another app is holding the file open and not accessible."))
  6524. return 'fail'
  6525. if self.defaults["global_open_style"] is False:
  6526. self.file_opened.emit("SVG", filename)
  6527. self.file_saved.emit("SVG", filename)
  6528. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6529. def save_source_file(self, obj_name, filename, use_thread=True):
  6530. """
  6531. Exports a FlatCAM Object to an Gerber/Excellon file.
  6532. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6533. :param filename: Path to the Gerber file to save to.
  6534. :param use_thread: if to be run in a separate thread
  6535. :return:
  6536. """
  6537. self.defaults.report_usage("save source file()")
  6538. if filename is None:
  6539. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6540. is not None else self.defaults["global_last_folder"]
  6541. self.log.debug("save source file()")
  6542. obj = self.collection.get_by_name(obj_name)
  6543. file_string = StringIO(obj.source_file)
  6544. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6545. if file_string.getvalue() == '':
  6546. self.inform.emit('[ERROR_NOTCL] %s' %
  6547. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6548. return 'fail'
  6549. try:
  6550. with open(filename, 'w') as file:
  6551. file.writelines('G04*\n')
  6552. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6553. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6554. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6555. file.writelines('G04 Created on : %s*\n' % time_string)
  6556. for line in file_string:
  6557. file.writelines(line)
  6558. except PermissionError:
  6559. self.inform.emit('[WARNING] %s' %
  6560. _("Permission denied, saving not possible.\n"
  6561. "Most likely another app is holding the file open and not accessible."))
  6562. return 'fail'
  6563. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6564. """
  6565. Exports a Excellon Object to an Excellon file.
  6566. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6567. :param filename: Path to the Excellon file to save to.
  6568. :param local_use:
  6569. :param use_thread: if to be run in a separate thread
  6570. :return:
  6571. """
  6572. self.defaults.report_usage("export_excellon()")
  6573. if filename is None:
  6574. if self.defaults["global_last_save_folder"]:
  6575. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6576. else:
  6577. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6578. self.log.debug("export_excellon()")
  6579. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6580. self.defaults["excellon_exp_decimals"]
  6581. )
  6582. if local_use is None:
  6583. try:
  6584. obj = self.collection.get_by_name(str(obj_name))
  6585. except Exception:
  6586. return "Could not retrieve object: %s" % obj_name
  6587. else:
  6588. obj = local_use
  6589. if not isinstance(obj, ExcellonObject):
  6590. self.inform.emit('[ERROR_NOTCL] %s' %
  6591. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6592. return
  6593. # updated units
  6594. eunits = self.defaults["excellon_exp_units"]
  6595. ewhole = self.defaults["excellon_exp_integer"]
  6596. efract = self.defaults["excellon_exp_decimals"]
  6597. ezeros = self.defaults["excellon_exp_zeros"]
  6598. eformat = self.defaults["excellon_exp_format"]
  6599. slot_type = self.defaults["excellon_exp_slot_type"]
  6600. fc_units = self.defaults['units'].upper()
  6601. if fc_units == 'MM':
  6602. factor = 1 if eunits == 'METRIC' else 0.03937
  6603. else:
  6604. factor = 25.4 if eunits == 'METRIC' else 1
  6605. def make_excellon():
  6606. try:
  6607. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6608. header = 'M48\n'
  6609. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6610. (str(self.version), str(self.version_date))
  6611. header += ';Filename: %s' % str(obj_name) + '\n'
  6612. header += ';Created on : %s' % time_str + '\n'
  6613. if eformat == 'dec':
  6614. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6615. header += eunits + '\n'
  6616. for tool in obj.tools:
  6617. if eunits == 'METRIC':
  6618. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6619. tool=str(tool),
  6620. dec=2)
  6621. else:
  6622. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6623. tool=str(tool),
  6624. dec=4)
  6625. else:
  6626. if ezeros == 'LZ':
  6627. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6628. form='ndec', e_zeros='LZ', factor=factor,
  6629. slot_type=slot_type)
  6630. header += '%s,%s\n' % (eunits, 'LZ')
  6631. header += format_exc
  6632. for tool in obj.tools:
  6633. if eunits == 'METRIC':
  6634. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6635. tool=str(tool),
  6636. dec=2)
  6637. else:
  6638. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6639. tool=str(tool),
  6640. dec=4)
  6641. else:
  6642. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6643. form='ndec', e_zeros='TZ', factor=factor,
  6644. slot_type=slot_type)
  6645. header += '%s,%s\n' % (eunits, 'TZ')
  6646. header += format_exc
  6647. for tool in obj.tools:
  6648. if eunits == 'METRIC':
  6649. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6650. tool=str(tool),
  6651. dec=2)
  6652. else:
  6653. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6654. tool=str(tool),
  6655. dec=4)
  6656. header += '%\n'
  6657. footer = 'M30\n'
  6658. exported_excellon = header
  6659. exported_excellon += excellon_code
  6660. exported_excellon += footer
  6661. if local_use is None:
  6662. try:
  6663. with open(filename, 'w') as fp:
  6664. fp.write(exported_excellon)
  6665. except PermissionError:
  6666. self.inform.emit('[WARNING] %s' %
  6667. _("Permission denied, saving not possible.\n"
  6668. "Most likely another app is holding the file open and not accessible."))
  6669. return 'fail'
  6670. if self.defaults["global_open_style"] is False:
  6671. self.file_opened.emit("Excellon", filename)
  6672. self.file_saved.emit("Excellon", filename)
  6673. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6674. else:
  6675. return exported_excellon
  6676. except Exception as e:
  6677. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6678. return 'fail'
  6679. if use_thread is True:
  6680. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6681. def job_thread_exc(app_obj):
  6682. ret = make_excellon()
  6683. if ret == 'fail':
  6684. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6685. return
  6686. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6687. else:
  6688. eret = make_excellon()
  6689. if eret == 'fail':
  6690. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6691. return 'fail'
  6692. if local_use is not None:
  6693. return eret
  6694. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6695. """
  6696. Exports a Gerber Object to an Gerber file.
  6697. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6698. :param filename: Path to the Gerber file to save to.
  6699. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6700. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6701. :param use_thread: if to be run in a separate thread
  6702. :return:
  6703. """
  6704. self.defaults.report_usage("export_gerber()")
  6705. if filename is None:
  6706. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6707. is not None else self.defaults["global_last_folder"]
  6708. self.log.debug("export_gerber()")
  6709. if local_use is None:
  6710. try:
  6711. obj = self.collection.get_by_name(str(obj_name))
  6712. except Exception:
  6713. return "Could not retrieve object: %s" % obj_name
  6714. else:
  6715. obj = local_use
  6716. # updated units
  6717. gunits = self.defaults["gerber_exp_units"]
  6718. gwhole = self.defaults["gerber_exp_integer"]
  6719. gfract = self.defaults["gerber_exp_decimals"]
  6720. gzeros = self.defaults["gerber_exp_zeros"]
  6721. fc_units = self.defaults['units'].upper()
  6722. if fc_units == 'MM':
  6723. factor = 1 if gunits == 'MM' else 0.03937
  6724. else:
  6725. factor = 25.4 if gunits == 'MM' else 1
  6726. def make_gerber():
  6727. try:
  6728. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6729. header = 'G04*\n'
  6730. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6731. (str(self.version), str(self.version_date))
  6732. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6733. header += 'G04 Created on : %s*' % time_str + '\n'
  6734. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6735. header += "%MO{units}*%\n".format(units=gunits)
  6736. for apid in obj.apertures:
  6737. if obj.apertures[apid]['type'] == 'C':
  6738. header += "%ADD{apid}{type},{size}*%\n".format(
  6739. apid=str(apid),
  6740. type='C',
  6741. size=(factor * obj.apertures[apid]['size'])
  6742. )
  6743. elif obj.apertures[apid]['type'] == 'R':
  6744. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6745. apid=str(apid),
  6746. type='R',
  6747. width=(factor * obj.apertures[apid]['width']),
  6748. height=(factor * obj.apertures[apid]['height'])
  6749. )
  6750. elif obj.apertures[apid]['type'] == 'O':
  6751. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6752. apid=str(apid),
  6753. type='O',
  6754. width=(factor * obj.apertures[apid]['width']),
  6755. height=(factor * obj.apertures[apid]['height'])
  6756. )
  6757. header += '\n'
  6758. # obsolete units but some software may need it
  6759. if gunits == 'IN':
  6760. header += 'G70*\n'
  6761. else:
  6762. header += 'G71*\n'
  6763. # Absolute Mode
  6764. header += 'G90*\n'
  6765. header += 'G01*\n'
  6766. # positive polarity
  6767. header += '%LPD*%\n'
  6768. footer = 'M02*\n'
  6769. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6770. exported_gerber = header
  6771. exported_gerber += gerber_code
  6772. exported_gerber += footer
  6773. if local_use is None:
  6774. try:
  6775. with open(filename, 'w') as fp:
  6776. fp.write(exported_gerber)
  6777. except PermissionError:
  6778. self.inform.emit('[WARNING] %s' %
  6779. _("Permission denied, saving not possible.\n"
  6780. "Most likely another app is holding the file open and not accessible."))
  6781. return 'fail'
  6782. if self.defaults["global_open_style"] is False:
  6783. self.file_opened.emit("Gerber", filename)
  6784. self.file_saved.emit("Gerber", filename)
  6785. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6786. else:
  6787. return exported_gerber
  6788. except Exception as e:
  6789. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6790. return 'fail'
  6791. if use_thread is True:
  6792. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6793. def job_thread_grb(app_obj):
  6794. ret = make_gerber()
  6795. if ret == 'fail':
  6796. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6797. return
  6798. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6799. else:
  6800. gret = make_gerber()
  6801. if gret == 'fail':
  6802. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6803. return 'fail'
  6804. if local_use is not None:
  6805. return gret
  6806. def export_dxf(self, obj_name, filename, use_thread=True):
  6807. """
  6808. Exports a Geometry Object to an DXF file.
  6809. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6810. :param filename: Path to the DXF file to save to.
  6811. :param use_thread: if to be run in a separate thread
  6812. :return:
  6813. """
  6814. self.defaults.report_usage("export_dxf()")
  6815. if filename is None:
  6816. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6817. is not None else self.defaults["global_last_folder"]
  6818. self.log.debug("export_dxf()")
  6819. try:
  6820. obj = self.collection.get_by_name(str(obj_name))
  6821. except Exception:
  6822. # TODO: The return behavior has not been established... should raise exception?
  6823. return "Could not retrieve object: %s" % obj_name
  6824. def make_dxf():
  6825. try:
  6826. dxf_code = obj.export_dxf()
  6827. dxf_code.saveas(filename)
  6828. if self.defaults["global_open_style"] is False:
  6829. self.file_opened.emit("DXF", filename)
  6830. self.file_saved.emit("DXF", filename)
  6831. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6832. except Exception:
  6833. return 'fail'
  6834. if use_thread is True:
  6835. with self.proc_container.new(_("Exporting DXF")) as proc:
  6836. def job_thread_exc(app_obj):
  6837. ret_dxf_val = make_dxf()
  6838. if ret_dxf_val == 'fail':
  6839. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6840. return
  6841. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6842. else:
  6843. ret = make_dxf()
  6844. if ret == 'fail':
  6845. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6846. return
  6847. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6848. """
  6849. Adds a new Geometry Object to the projects and populates
  6850. it with shapes extracted from the SVG file.
  6851. :param plot: If True then the resulting object will be plotted on canvas
  6852. :param filename: Path to the SVG file.
  6853. :param geo_type: Type of FlatCAM object that will be created from SVG
  6854. :param outname: The name given to the resulting FlatCAM object
  6855. :return:
  6856. """
  6857. self.defaults.report_usage("import_svg()")
  6858. log.debug("App.import_svg()")
  6859. obj_type = ""
  6860. if geo_type is None or geo_type == "geometry":
  6861. obj_type = "geometry"
  6862. elif geo_type == "gerber":
  6863. obj_type = "gerber"
  6864. else:
  6865. self.inform.emit('[ERROR_NOTCL] %s' %
  6866. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6867. return
  6868. units = self.defaults['units'].upper()
  6869. def obj_init(geo_obj, app_obj):
  6870. geo_obj.import_svg(filename, obj_type, units=units)
  6871. geo_obj.multigeo = False
  6872. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6873. with self.proc_container.new(_("Importing SVG")) as proc:
  6874. # Object name
  6875. name = outname or filename.split('/')[-1].split('\\')[-1]
  6876. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6877. if ret == 'fail':
  6878. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6879. return 'fail'
  6880. # Register recent file
  6881. self.file_opened.emit("svg", filename)
  6882. # AppGUI feedback
  6883. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6884. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6885. """
  6886. Adds a new Geometry Object to the projects and populates
  6887. it with shapes extracted from the DXF file.
  6888. :param filename: Path to the DXF file.
  6889. :param geo_type: Type of FlatCAM object that will be created from DXF
  6890. :param outname: Name for the imported Geometry
  6891. :param plot: If True then the resulting object will be plotted on canvas
  6892. :return:
  6893. """
  6894. self.defaults.report_usage("import_dxf()")
  6895. obj_type = ""
  6896. if geo_type is None or geo_type == "geometry":
  6897. obj_type = "geometry"
  6898. elif geo_type == "gerber":
  6899. obj_type = geo_type
  6900. else:
  6901. self.inform.emit('[ERROR_NOTCL] %s' %
  6902. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6903. return
  6904. units = self.defaults['units'].upper()
  6905. def obj_init(geo_obj, app_obj):
  6906. geo_obj.import_dxf(filename, obj_type, units=units)
  6907. geo_obj.multigeo = False
  6908. with self.proc_container.new(_("Importing DXF")):
  6909. # Object name
  6910. name = outname or filename.split('/')[-1].split('\\')[-1]
  6911. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6912. if ret == 'fail':
  6913. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6914. return 'fail'
  6915. # Register recent file
  6916. self.file_opened.emit("dxf", filename)
  6917. # AppGUI feedback
  6918. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6919. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6920. """
  6921. Opens a Gerber file, parses it and creates a new object for
  6922. it in the program. Thread-safe.
  6923. :param outname: Name of the resulting object. None causes the
  6924. name to be that of the file. Str.
  6925. :param filename: Gerber file filename
  6926. :type filename: str
  6927. :param plot: boolean, to plot or not the resulting object
  6928. :param from_tcl: True if run from Tcl Shell
  6929. :return: None
  6930. """
  6931. # How the object should be initialized
  6932. def obj_init(gerber_obj, app_obj):
  6933. assert isinstance(gerber_obj, GerberObject), \
  6934. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6935. # Opening the file happens here
  6936. try:
  6937. gerber_obj.parse_file(filename)
  6938. except IOError:
  6939. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6940. return "fail"
  6941. except ParseError as err:
  6942. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6943. app_obj.log.error(str(err))
  6944. return "fail"
  6945. except Exception as e:
  6946. log.debug("App.open_gerber() --> %s" % str(e))
  6947. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6948. msg += traceback.format_exc()
  6949. app_obj.inform.emit(msg)
  6950. return "fail"
  6951. if gerber_obj.is_empty():
  6952. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6953. _("Object is not Gerber file or empty. Aborting object creation."))
  6954. return "fail"
  6955. App.log.debug("open_gerber()")
  6956. with self.proc_container.new(_("Opening Gerber")):
  6957. # Object name
  6958. name = outname or filename.split('/')[-1].split('\\')[-1]
  6959. # # ## Object creation # ##
  6960. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6961. if ret_val == 'fail':
  6962. if from_tcl:
  6963. filename = self.defaults['global_tcl_path'] + '/' + name
  6964. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6965. if ret_val == 'fail':
  6966. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6967. return 'fail'
  6968. # Register recent file
  6969. self.file_opened.emit("gerber", filename)
  6970. # AppGUI feedback
  6971. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6972. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6973. """
  6974. Opens an Excellon file, parses it and creates a new object for
  6975. it in the program. Thread-safe.
  6976. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6977. :param filename: Excellon file filename
  6978. :type filename: str
  6979. :param plot: boolean, to plot or not the resulting object
  6980. :param from_tcl: True if run from Tcl Shell
  6981. :return: None
  6982. """
  6983. App.log.debug("open_excellon()")
  6984. # How the object should be initialized
  6985. def obj_init(excellon_obj, app_obj):
  6986. try:
  6987. ret = excellon_obj.parse_file(filename=filename)
  6988. if ret == "fail":
  6989. log.debug("Excellon parsing failed.")
  6990. self.inform.emit('[ERROR_NOTCL] %s' %
  6991. _("This is not Excellon file."))
  6992. return "fail"
  6993. except IOError:
  6994. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6995. (_("Cannot open file"), filename))
  6996. log.debug("Could not open Excellon object.")
  6997. return "fail"
  6998. except Exception:
  6999. msg = '[ERROR_NOTCL] %s' % \
  7000. _("An internal error has occurred. See shell.\n")
  7001. msg += traceback.format_exc()
  7002. app_obj.inform.emit(msg)
  7003. return "fail"
  7004. ret = excellon_obj.create_geometry()
  7005. if ret == 'fail':
  7006. log.debug("Could not create geometry for Excellon object.")
  7007. return "fail"
  7008. for tool in excellon_obj.tools:
  7009. if excellon_obj.tools[tool]['solid_geometry']:
  7010. return
  7011. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7012. return "fail"
  7013. with self.proc_container.new(_("Opening Excellon.")):
  7014. # Object name
  7015. name = outname or filename.split('/')[-1].split('\\')[-1]
  7016. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7017. if ret_val == 'fail':
  7018. if from_tcl:
  7019. filename = self.defaults['global_tcl_path'] + '/' + name
  7020. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7021. if ret_val == 'fail':
  7022. self.inform.emit('[ERROR_NOTCL] %s' %
  7023. _('Open Excellon file failed. Probable not an Excellon file.'))
  7024. return
  7025. # Register recent file
  7026. self.file_opened.emit("excellon", filename)
  7027. # AppGUI feedback
  7028. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7029. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7030. """
  7031. Opens a G-gcode file, parses it and creates a new object for
  7032. it in the program. Thread-safe.
  7033. :param filename: G-code file filename
  7034. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7035. :param force_parsing:
  7036. :param plot: If True plot the object on canvas
  7037. :param from_tcl: True if run from Tcl Shell
  7038. :return: None
  7039. """
  7040. App.log.debug("open_gcode()")
  7041. # How the object should be initialized
  7042. def obj_init(job_obj, app_obj_):
  7043. """
  7044. :param job_obj: the resulting object
  7045. :type app_obj_: App
  7046. """
  7047. assert isinstance(app_obj_, App), \
  7048. "Initializer expected App, got %s" % type(app_obj_)
  7049. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7050. try:
  7051. f = open(filename)
  7052. gcode = f.read()
  7053. f.close()
  7054. except IOError:
  7055. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7056. return "fail"
  7057. job_obj.gcode = gcode
  7058. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7059. if gcode_ret == "fail":
  7060. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7061. return "fail"
  7062. job_obj.create_geometry()
  7063. with self.proc_container.new(_("Opening G-Code.")):
  7064. # Object name
  7065. name = outname or filename.split('/')[-1].split('\\')[-1]
  7066. # New object creation and file processing
  7067. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7068. if ret_val == 'fail':
  7069. if from_tcl:
  7070. filename = self.defaults['global_tcl_path'] + '/' + name
  7071. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7072. if ret_val == 'fail':
  7073. self.inform.emit('[ERROR_NOTCL] %s' %
  7074. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7075. "Try to load it from File menu.\n "
  7076. "Attempting to create a FlatCAM CNCJob Object from "
  7077. "G-Code file failed during processing"))
  7078. return "fail"
  7079. # Register recent file
  7080. self.file_opened.emit("cncjob", filename)
  7081. # AppGUI feedback
  7082. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7083. def open_hpgl2(self, filename, outname=None):
  7084. """
  7085. Opens a HPGL2 file, parses it and creates a new object for
  7086. it in the program. Thread-safe.
  7087. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7088. :param filename: HPGL2 file filename
  7089. :return: None
  7090. """
  7091. filename = filename
  7092. # How the object should be initialized
  7093. def obj_init(geo_obj, app_obj):
  7094. assert isinstance(geo_obj, GeometryObject), \
  7095. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7096. # Opening the file happens here
  7097. obj = HPGL2(self)
  7098. try:
  7099. HPGL2.parse_file(obj, filename)
  7100. except IOError:
  7101. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7102. return "fail"
  7103. except ParseError as err:
  7104. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7105. app_obj.log.error(str(err))
  7106. return "fail"
  7107. except Exception as e:
  7108. log.debug("App.open_hpgl2() --> %s" % str(e))
  7109. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7110. msg += traceback.format_exc()
  7111. app_obj.inform.emit(msg)
  7112. return "fail"
  7113. geo_obj.multigeo = True
  7114. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7115. geo_obj.tools = deepcopy(obj.tools)
  7116. geo_obj.source_file = deepcopy(obj.source_file)
  7117. del obj
  7118. if not geo_obj.solid_geometry:
  7119. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7120. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7121. return "fail"
  7122. App.log.debug("open_hpgl2()")
  7123. with self.proc_container.new(_("Opening HPGL2")):
  7124. # Object name
  7125. name = outname or filename.split('/')[-1].split('\\')[-1]
  7126. # # ## Object creation # ##
  7127. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7128. if ret == 'fail':
  7129. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7130. return 'fail'
  7131. # Register recent file
  7132. self.file_opened.emit("geometry", filename)
  7133. # AppGUI feedback
  7134. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7135. def open_script(self, filename, outname=None, silent=False):
  7136. """
  7137. Opens a Script file, parses it and creates a new object for
  7138. it in the program. Thread-safe.
  7139. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7140. :param filename: Script file filename
  7141. :param silent: If True there will be no messages printed to StatusBar
  7142. :return: None
  7143. """
  7144. def obj_init(script_obj, app_obj):
  7145. assert isinstance(script_obj, ScriptObject), \
  7146. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7147. if silent is False:
  7148. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7149. try:
  7150. script_obj.parse_file(filename)
  7151. except IOError:
  7152. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7153. return "fail"
  7154. except ParseError as err:
  7155. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7156. app_obj.log.error(str(err))
  7157. return "fail"
  7158. except Exception as e:
  7159. log.debug("App.open_script() -> %s" % str(e))
  7160. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7161. msg += traceback.format_exc()
  7162. app_obj.inform.emit(msg)
  7163. return "fail"
  7164. App.log.debug("open_script()")
  7165. with self.proc_container.new(_("Opening TCL Script...")):
  7166. # Object name
  7167. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7168. # Object creation
  7169. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7170. if ret_val == 'fail':
  7171. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7172. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7173. if ret_val == 'fail':
  7174. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7175. return 'fail'
  7176. # Register recent file
  7177. self.file_opened.emit("script", filename)
  7178. # AppGUI feedback
  7179. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7180. def open_config_file(self, filename, run_from_arg=None):
  7181. """
  7182. Loads a config file from the specified file.
  7183. :param filename: Name of the file from which to load.
  7184. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7185. :return: None
  7186. """
  7187. App.log.debug("Opening config file: " + filename)
  7188. if run_from_arg:
  7189. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7190. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7191. _("Opening FlatCAM Config file.")),
  7192. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7193. color=QtGui.QColor("gray"))
  7194. # # add the tab if it was closed
  7195. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7196. # # first clear previous text in text editor (if any)
  7197. # self.ui.text_editor_tab.code_editor.clear()
  7198. #
  7199. # # Switch plot_area to CNCJob tab
  7200. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7201. # close the Code editor if already open
  7202. if self.toggle_codeeditor:
  7203. self.on_toggle_code_editor()
  7204. self.on_toggle_code_editor()
  7205. try:
  7206. if filename:
  7207. f = QtCore.QFile(filename)
  7208. if f.open(QtCore.QIODevice.ReadOnly):
  7209. stream = QtCore.QTextStream(f)
  7210. code_edited = stream.readAll()
  7211. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7212. f.close()
  7213. except IOError:
  7214. App.log.error("Failed to open config file: %s" % filename)
  7215. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7216. (_("Failed to open config file"), filename))
  7217. return
  7218. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7219. """
  7220. Loads a project from the specified file.
  7221. 1) Loads and parses file
  7222. 2) Registers the file as recently opened.
  7223. 3) Calls on_file_new()
  7224. 4) Updates options
  7225. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7226. 6) Calls plot_all() if plot=True
  7227. :param filename: Name of the file from which to load.
  7228. :param run_from_arg: True if run for arguments
  7229. :param plot: If True plot all objects in the project
  7230. :param cli: Run from command line
  7231. :param from_tcl: True if run from Tcl Sehll
  7232. :return: None
  7233. """
  7234. App.log.debug("Opening project: " + filename)
  7235. # block autosaving while a project is loaded
  7236. self.block_autosave = True
  7237. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7238. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7239. if cli is None:
  7240. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7241. if run_from_arg:
  7242. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7243. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7244. _("Opening FlatCAM Project file.")),
  7245. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7246. color=QtGui.QColor("gray"))
  7247. # Open and parse an uncompressed Project file
  7248. try:
  7249. f = open(filename, 'r')
  7250. except IOError:
  7251. if from_tcl:
  7252. name = filename.split('/')[-1].split('\\')[-1]
  7253. filename = self.defaults['global_tcl_path'] + '/' + name
  7254. try:
  7255. f = open(filename, 'r')
  7256. except IOError:
  7257. log.error("Failed to open project file: %s" % filename)
  7258. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7259. return
  7260. else:
  7261. log.error("Failed to open project file: %s" % filename)
  7262. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7263. return
  7264. try:
  7265. d = json.load(f, object_hook=dict2obj)
  7266. except Exception as e:
  7267. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7268. (filename, str(e)))
  7269. f.close()
  7270. # Open and parse a compressed Project file
  7271. try:
  7272. with lzma.open(filename) as f:
  7273. file_content = f.read().decode('utf-8')
  7274. d = json.loads(file_content, object_hook=dict2obj)
  7275. except Exception as e:
  7276. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7277. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7278. return
  7279. # Clear the current project
  7280. # # NOT THREAD SAFE # ##
  7281. if run_from_arg is True:
  7282. pass
  7283. elif cli is True:
  7284. self.delete_selection_shape()
  7285. else:
  7286. self.on_file_new()
  7287. # Project options
  7288. self.options.update(d['options'])
  7289. self.project_filename = filename
  7290. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7291. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7292. if cli is None:
  7293. self.set_screen_units(self.options["units"])
  7294. # Re create objects
  7295. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7296. for obj in d['objs']:
  7297. try:
  7298. def obj_init(obj_inst, app_inst):
  7299. obj_inst.from_dict(obj)
  7300. App.log.debug("Recreating from opened project an %s object: %s" %
  7301. (obj['kind'].capitalize(), obj['options']['name']))
  7302. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7303. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7304. if cli is None:
  7305. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7306. obj['kind'].upper(),
  7307. obj['options']['name']
  7308. )
  7309. )
  7310. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7311. except Exception as e:
  7312. print('App.open_project() --> ' + str(e))
  7313. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7314. self.should_we_save = False
  7315. self.file_opened.emit("project", filename)
  7316. # restore autosaving after a project was loaded
  7317. self.block_autosave = False
  7318. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7319. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7320. if cli is None:
  7321. self.set_ui_title(name=self.project_filename)
  7322. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7323. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7324. """
  7325. Re-generates all plots from all objects.
  7326. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7327. :param muted: if True don't print messages
  7328. :param use_thread: if True will use threading for plotting the objects
  7329. :return: None
  7330. """
  7331. self.log.debug("Plot_all()")
  7332. if muted is not True:
  7333. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7334. for plot_obj in self.collection.get_list():
  7335. def worker_task(obj):
  7336. with self.proc_container.new("Plotting"):
  7337. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7338. if fit_view is True:
  7339. self.app_obj.object_plotted.emit(obj)
  7340. if use_thread is True:
  7341. # Send to worker
  7342. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7343. else:
  7344. worker_task(plot_obj)
  7345. def register_folder(self, filename):
  7346. """
  7347. Register the last folder used by the app to open something
  7348. :param filename: the last folder is extracted from the filename
  7349. :return: None
  7350. """
  7351. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7352. def register_save_folder(self, filename):
  7353. """
  7354. Register the last folder used by the app to save something
  7355. :param filename: the last folder is extracted from the filename
  7356. :return: None
  7357. """
  7358. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7359. # def set_progress_bar(self, percentage, text=""):
  7360. # """
  7361. # Set a progress bar to a value (percentage)
  7362. #
  7363. # :param percentage: Value set to the progressbar
  7364. # :param text: Not used
  7365. # :return: None
  7366. # """
  7367. # self.ui.progress_bar.setValue(int(percentage))
  7368. def setup_recent_items(self):
  7369. """
  7370. Setup a dictionary with the recent files accessed, organized by type
  7371. :return:
  7372. """
  7373. icons = {
  7374. "gerber": self.resource_location + "/flatcam_icon16.png",
  7375. "excellon": self.resource_location + "/drill16.png",
  7376. 'geometry': self.resource_location + "/geometry16.png",
  7377. "cncjob": self.resource_location + "/cnc16.png",
  7378. "script": self.resource_location + "/script_new24.png",
  7379. "document": self.resource_location + "/notes16_1.png",
  7380. "project": self.resource_location + "/project16.png",
  7381. "svg": self.resource_location + "/geometry16.png",
  7382. "dxf": self.resource_location + "/dxf16.png",
  7383. "pdf": self.resource_location + "/pdf32.png",
  7384. "image": self.resource_location + "/image16.png"
  7385. }
  7386. try:
  7387. image_opener = self.image_tool.import_image
  7388. except AttributeError:
  7389. image_opener = None
  7390. openers = {
  7391. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7392. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7393. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7394. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7395. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7396. "document": None,
  7397. 'project': self.open_project,
  7398. 'svg': self.import_svg,
  7399. 'dxf': self.import_dxf,
  7400. 'image': image_opener,
  7401. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7402. }
  7403. # Open recent file for files
  7404. try:
  7405. f = open(self.data_path + '/recent.json')
  7406. except IOError:
  7407. App.log.error("Failed to load recent item list.")
  7408. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7409. return
  7410. try:
  7411. self.recent = json.load(f)
  7412. except json.errors.JSONDecodeError:
  7413. App.log.error("Failed to parse recent item list.")
  7414. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7415. f.close()
  7416. return
  7417. f.close()
  7418. # Open recent file for projects
  7419. try:
  7420. fp = open(self.data_path + '/recent_projects.json')
  7421. except IOError:
  7422. App.log.error("Failed to load recent project item list.")
  7423. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7424. return
  7425. try:
  7426. self.recent_projects = json.load(fp)
  7427. except json.errors.JSONDecodeError:
  7428. App.log.error("Failed to parse recent project item list.")
  7429. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7430. fp.close()
  7431. return
  7432. fp.close()
  7433. # Closure needed to create callbacks in a loop.
  7434. # Otherwise late binding occurs.
  7435. def make_callback(func, fname):
  7436. def opener():
  7437. func(fname)
  7438. return opener
  7439. def reset_recent_files():
  7440. # Reset menu
  7441. self.ui.recent.clear()
  7442. self.recent = []
  7443. try:
  7444. ff = open(self.data_path + '/recent.json', 'w')
  7445. except IOError:
  7446. App.log.error("Failed to open recent items file for writing.")
  7447. return
  7448. json.dump(self.recent, ff)
  7449. def reset_recent_projects():
  7450. # Reset menu
  7451. self.ui.recent_projects.clear()
  7452. self.recent_projects = []
  7453. try:
  7454. frp = open(self.data_path + '/recent_projects.json', 'w')
  7455. except IOError:
  7456. App.log.error("Failed to open recent projects items file for writing.")
  7457. return
  7458. json.dump(self.recent, frp)
  7459. # Reset menu
  7460. self.ui.recent.clear()
  7461. self.ui.recent_projects.clear()
  7462. # Create menu items for projects
  7463. for recent in self.recent_projects:
  7464. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7465. if recent['kind'] == 'project':
  7466. try:
  7467. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7468. # Attach callback
  7469. o = make_callback(openers[recent["kind"]], recent['filename'])
  7470. action.triggered.connect(o)
  7471. self.ui.recent_projects.addAction(action)
  7472. except KeyError:
  7473. App.log.error("Unsupported file type: %s" % recent["kind"])
  7474. # Last action in Recent Files menu is one that Clear the content
  7475. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7476. (_("Clear Recent projects")), self)
  7477. clear_action_proj.triggered.connect(reset_recent_projects)
  7478. self.ui.recent_projects.addSeparator()
  7479. self.ui.recent_projects.addAction(clear_action_proj)
  7480. # Create menu items for files
  7481. for recent in self.recent:
  7482. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7483. if recent['kind'] != 'project':
  7484. try:
  7485. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7486. # Attach callback
  7487. o = make_callback(openers[recent["kind"]], recent['filename'])
  7488. action.triggered.connect(o)
  7489. self.ui.recent.addAction(action)
  7490. except KeyError:
  7491. App.log.error("Unsupported file type: %s" % recent["kind"])
  7492. # Last action in Recent Files menu is one that Clear the content
  7493. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7494. (_("Clear Recent files")), self)
  7495. clear_action.triggered.connect(reset_recent_files)
  7496. self.ui.recent.addSeparator()
  7497. self.ui.recent.addAction(clear_action)
  7498. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7499. # self.ui.menufilerecent.set_submenu(recent_menu)
  7500. # recent_menu.show_all()
  7501. # self.ui.recent.show()
  7502. self.log.debug("Recent items list has been populated.")
  7503. def setup_component_editor(self):
  7504. """
  7505. Default text for the Selected tab when is not taken by the Object UI.
  7506. :return:
  7507. """
  7508. # label = QtWidgets.QLabel("Choose an item from Project")
  7509. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7510. sel_title = QtWidgets.QTextEdit(
  7511. _('<b>Shortcut Key List</b>'))
  7512. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7513. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7514. f_settings = QSettings("Open Source", "FlatCAM")
  7515. if f_settings.contains("notebook_font_size"):
  7516. fsize = f_settings.value('notebook_font_size', type=int)
  7517. else:
  7518. fsize = 12
  7519. tsize = fsize + int(fsize / 2)
  7520. # selected_text = (_('''
  7521. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7522. # </p>
  7523. #
  7524. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7525. # The normal flow when working in FlatCAM is the following:</span></p>
  7526. #
  7527. # <ol>
  7528. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7529. # file into
  7530. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7531. # even dragging and dropping the files on the AppGUI.<br />
  7532. # <br />
  7533. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7534. # drop of the
  7535. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7536. # &nbsp;</li>
  7537. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7538. # and then
  7539. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7540. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7541. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7542. # <br />
  7543. # If the selection of the object is done on the canvas by single click instead, and the
  7544. # <strong>SELECTED TAB</strong>
  7545. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7546. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7547. # it even if it was out of focus.<br />
  7548. # <br />
  7549. # You can change the parameters in this screen and the flow direction is like this:<br />
  7550. # <br />
  7551. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7552. # <strong> Geometry Object
  7553. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7554. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7555. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7556. # </ol>
  7557. #
  7558. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7559. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7560. # <strong>F3</strong>.</span></p>
  7561. #
  7562. # ''').format(fsize=fsize, tsize=tsize))
  7563. selected_text = '''
  7564. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7565. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7566. {s1}</span></p>
  7567. <ol>
  7568. <li><span style="font-size:{fsize}px">{s2}<br />
  7569. <br />
  7570. {s3}</span><br />
  7571. &nbsp;</li>
  7572. <li><span style="font-size:{fsize}px">{s4}<br />
  7573. &nbsp;</li>
  7574. <br />
  7575. <li><span style="font-size:{fsize}px">{s5}<br />
  7576. &nbsp;</li>
  7577. <br />
  7578. <li><span style="font-size:{fsize}px">{s6}<br />
  7579. <br />
  7580. {s7}</span></li>
  7581. </ol>
  7582. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7583. '''.format(
  7584. title=_("Selected Tab - Choose an Item from Project Tab"),
  7585. subtitle=_("Details"),
  7586. s1=_("The normal flow when working in FlatCAM is the following:"),
  7587. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7588. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7589. "files on the AppGUI."),
  7590. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7591. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7592. "actions offered within the app."),
  7593. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7594. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7595. "SELECTED TAB will be updated with the object properties according to its kind: "
  7596. "Gerber, Excellon, Geometry or CNCJob object."),
  7597. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7598. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7599. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7600. "the SELECTED TAB and populate it even if it was out of focus."),
  7601. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7602. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7603. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7604. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7605. "(again, done in SELECTED TAB) --> Save GCode."),
  7606. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7607. "or through its own key shortcut: <b>F3</b>."),
  7608. tsize=tsize,
  7609. fsize=fsize
  7610. )
  7611. sel_title.setText(selected_text)
  7612. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7613. self.ui.selected_scroll_area.setWidget(sel_title)
  7614. def setup_obj_classes(self):
  7615. """
  7616. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7617. class.
  7618. :return: None
  7619. """
  7620. FlatCAMObj.app = self
  7621. ObjectCollection.app = self
  7622. Gerber.app = self
  7623. Excellon.app = self
  7624. Geometry.app = self
  7625. CNCjob.app = self
  7626. FCProcess.app = self
  7627. FCProcessContainer.app = self
  7628. OptionsGroupUI.app = self
  7629. def version_check(self):
  7630. """
  7631. Checks for the latest version of the program. Alerts the
  7632. user if theirs is outdated. This method is meant to be run
  7633. in a separate thread.
  7634. :return: None
  7635. """
  7636. self.log.debug("version_check()")
  7637. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7638. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7639. App.version_url,
  7640. str(self.defaults['global_serial']),
  7641. str(self.version),
  7642. str(self.os),
  7643. urllib.parse.urlencode(self.defaults["global_stats"])
  7644. )
  7645. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7646. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7647. # urllib.parse.urlencode(self.defaults["global_stats"])
  7648. else:
  7649. # no_stats dict; just so it won't break things on website
  7650. no_ststs_dict = {}
  7651. no_ststs_dict["global_ststs"] = {}
  7652. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7653. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7654. App.log.debug("Checking for updates @ %s" % full_url)
  7655. # ## Get the data
  7656. try:
  7657. f = urllib.request.urlopen(full_url)
  7658. except Exception:
  7659. # App.log.warning("Failed checking for latest version. Could not connect.")
  7660. self.log.warning("Failed checking for latest version. Could not connect.")
  7661. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7662. return
  7663. try:
  7664. data = json.load(f)
  7665. except Exception as e:
  7666. App.log.error("Could not parse information about latest version.")
  7667. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7668. App.log.debug("json.load(): %s" % str(e))
  7669. f.close()
  7670. return
  7671. f.close()
  7672. # ## Latest version?
  7673. if self.version >= data["version"]:
  7674. App.log.debug("FlatCAM is up to date!")
  7675. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7676. return
  7677. App.log.debug("Newer version available.")
  7678. self.message.emit(
  7679. _("Newer Version Available"),
  7680. '%s<br><br>><b>%s</b><br>%s' % (
  7681. _("There is a newer version of FlatCAM available for download:"),
  7682. str(data["name"]),
  7683. str(data["message"])
  7684. ),
  7685. _("info")
  7686. )
  7687. def on_plotcanvas_setup(self, container=None):
  7688. """
  7689. This is doing the setup for the plot area (canvas).
  7690. :param container: QT Widget where to install the canvas
  7691. :return: None
  7692. """
  7693. if container:
  7694. plot_container = container
  7695. else:
  7696. plot_container = self.ui.right_layout
  7697. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7698. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7699. self.is_legacy = True
  7700. self.defaults["global_graphic_engine"] = "2D"
  7701. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7702. else:
  7703. try:
  7704. self.plotcanvas = PlotCanvas(plot_container, self)
  7705. except Exception as er:
  7706. msg_txt = traceback.format_exc()
  7707. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7708. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7709. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7710. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7711. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7712. msg += msg_txt
  7713. self.inform.emit(msg)
  7714. return 'fail'
  7715. # So it can receive key presses
  7716. self.plotcanvas.native.setFocus()
  7717. if self.is_legacy is False:
  7718. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7719. # Set the mouse button for panning
  7720. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7721. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7722. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7723. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7724. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7725. # Keys over plot enabled
  7726. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7727. if self.defaults['global_cursor_type'] == 'small':
  7728. self.app_cursor = self.plotcanvas.new_cursor()
  7729. else:
  7730. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7731. if self.ui.grid_snap_btn.isChecked():
  7732. self.app_cursor.enabled = True
  7733. else:
  7734. self.app_cursor.enabled = False
  7735. if self.is_legacy is False:
  7736. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7737. else:
  7738. # will use the default Matplotlib axes
  7739. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7740. def on_zoom_fit(self):
  7741. """
  7742. Callback for zoom-fit request. This can be either from the corresponding
  7743. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7744. with axes limits from the geometry bounds of all objects.
  7745. :return: None
  7746. """
  7747. if self.is_legacy is False:
  7748. self.plotcanvas.fit_view()
  7749. else:
  7750. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7751. width = xmax - xmin
  7752. height = ymax - ymin
  7753. xmin -= 0.05 * width
  7754. xmax += 0.05 * width
  7755. ymin -= 0.05 * height
  7756. ymax += 0.05 * height
  7757. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7758. def on_zoom_in(self):
  7759. """
  7760. Callback for zoom-in request.
  7761. :return:
  7762. """
  7763. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7764. def on_zoom_out(self):
  7765. """
  7766. Callback for zoom-out request.
  7767. :return:
  7768. """
  7769. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7770. def disable_all_plots(self):
  7771. self.defaults.report_usage("disable_all_plots()")
  7772. self.disable_plots(self.collection.get_list())
  7773. self.inform.emit('[success] %s' %
  7774. _("All plots disabled."))
  7775. def disable_other_plots(self):
  7776. self.defaults.report_usage("disable_other_plots()")
  7777. self.disable_plots(self.collection.get_non_selected())
  7778. self.inform.emit('[success] %s' %
  7779. _("All non selected plots disabled."))
  7780. def enable_all_plots(self):
  7781. self.defaults.report_usage("enable_all_plots()")
  7782. self.enable_plots(self.collection.get_list())
  7783. self.inform.emit('[success] %s' %
  7784. _("All plots enabled."))
  7785. def on_enable_sel_plots(self):
  7786. log.debug("App.on_enable_sel_plot()")
  7787. object_list = self.collection.get_selected()
  7788. self.enable_plots(objects=object_list)
  7789. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7790. def on_disable_sel_plots(self):
  7791. log.debug("App.on_disable_sel_plot()")
  7792. # self.inform.emit(_("Disabling plots ..."))
  7793. object_list = self.collection.get_selected()
  7794. self.disable_plots(objects=object_list)
  7795. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7796. def enable_plots(self, objects):
  7797. """
  7798. Enable plots
  7799. :param objects: list of Objects to be enabled
  7800. :return:
  7801. """
  7802. log.debug("Enabling plots ...")
  7803. # self.inform.emit(_("Working ..."))
  7804. for obj in objects:
  7805. if obj.options['plot'] is False:
  7806. obj.options.set_change_callback(lambda x: None)
  7807. obj.options['plot'] = True
  7808. try:
  7809. # only the Gerber obj has on_plot_cb_click() method
  7810. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7811. # disable this cb while disconnected,
  7812. # in case the operation takes time the user is not allowed to change it
  7813. obj.ui.plot_cb.setDisabled(True)
  7814. except AttributeError:
  7815. pass
  7816. obj.set_form_item("plot")
  7817. try:
  7818. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7819. obj.ui.plot_cb.setDisabled(False)
  7820. except AttributeError:
  7821. pass
  7822. obj.options.set_change_callback(obj.on_options_change)
  7823. def worker_task(objs):
  7824. with self.proc_container.new(_("Enabling plots ...")):
  7825. for plot_obj in objs:
  7826. # obj.options['plot'] = True
  7827. if isinstance(plot_obj, CNCJobObject):
  7828. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7829. else:
  7830. plot_obj.plot(visible=True)
  7831. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7832. def disable_plots(self, objects):
  7833. """
  7834. Disables plots
  7835. :param objects: list of Objects to be disabled
  7836. :return:
  7837. """
  7838. # if no objects selected then do nothing
  7839. if not self.collection.get_selected():
  7840. return
  7841. log.debug("Disabling plots ...")
  7842. # self.inform.emit(_("Working ..."))
  7843. for obj in objects:
  7844. if obj.options['plot'] is True:
  7845. obj.options.set_change_callback(lambda x: None)
  7846. obj.options['plot'] = False
  7847. try:
  7848. # only the Gerber obj has on_plot_cb_click() method
  7849. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7850. obj.ui.plot_cb.setDisabled(True)
  7851. except AttributeError:
  7852. pass
  7853. obj.set_form_item("plot")
  7854. try:
  7855. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7856. obj.ui.plot_cb.setDisabled(False)
  7857. except AttributeError:
  7858. pass
  7859. obj.options.set_change_callback(obj.on_options_change)
  7860. try:
  7861. self.delete_selection_shape()
  7862. except Exception as e:
  7863. log.debug("App.disable_plots() --> %s" % str(e))
  7864. def worker_task(objs):
  7865. with self.proc_container.new(_("Disabling plots ...")):
  7866. for plot_obj in objs:
  7867. # obj.options['plot'] = True
  7868. if isinstance(plot_obj, CNCJobObject):
  7869. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7870. else:
  7871. plot_obj.plot(visible=False)
  7872. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7873. def toggle_plots(self, objects):
  7874. """
  7875. Toggle plots visibility
  7876. :param objects: list of Objects for which to be toggled the visibility
  7877. :return: None
  7878. """
  7879. # if no objects selected then do nothing
  7880. if not self.collection.get_selected():
  7881. return
  7882. log.debug("Toggling plots ...")
  7883. self.inform.emit(_("Working ..."))
  7884. for obj in objects:
  7885. if obj.options['plot'] is False:
  7886. obj.options['plot'] = True
  7887. else:
  7888. obj.options['plot'] = False
  7889. self.app_obj.plots_updated.emit()
  7890. def clear_plots(self):
  7891. """
  7892. Clear the plots
  7893. :return: None
  7894. """
  7895. objects = self.collection.get_list()
  7896. for obj in objects:
  7897. obj.clear(obj == objects[-1])
  7898. # Clear pool to free memory
  7899. self.clear_pool()
  7900. def on_set_color_action_triggered(self):
  7901. """
  7902. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7903. :return:
  7904. """
  7905. new_color = self.defaults['gerber_plot_fill']
  7906. clicked_action = self.sender()
  7907. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7908. act_name = clicked_action.text()
  7909. sel_obj_list = self.collection.get_selected()
  7910. if not sel_obj_list:
  7911. return
  7912. # a default value, I just chose this one
  7913. alpha_level = 'BF'
  7914. for sel_obj in sel_obj_list:
  7915. if sel_obj.kind == 'excellon':
  7916. alpha_level = str(hex(
  7917. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7918. elif sel_obj.kind == 'gerber':
  7919. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7920. elif sel_obj.kind == 'geometry':
  7921. alpha_level = 'FF'
  7922. else:
  7923. log.debug(
  7924. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7925. continue
  7926. sel_obj.alpha_level = alpha_level
  7927. if act_name == _('Red'):
  7928. new_color = '#FF0000' + alpha_level
  7929. if act_name == _('Blue'):
  7930. new_color = '#0000FF' + alpha_level
  7931. if act_name == _('Yellow'):
  7932. new_color = '#FFDF00' + alpha_level
  7933. if act_name == _('Green'):
  7934. new_color = '#00FF00' + alpha_level
  7935. if act_name == _('Purple'):
  7936. new_color = '#FF00FF' + alpha_level
  7937. if act_name == _('Brown'):
  7938. new_color = '#A52A2A' + alpha_level
  7939. if act_name == _('White'):
  7940. new_color = '#FFFFFF' + alpha_level
  7941. if act_name == _('Black'):
  7942. new_color = '#000000' + alpha_level
  7943. if act_name == _('Custom'):
  7944. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7945. c_dialog = QtWidgets.QColorDialog()
  7946. plot_fill_color = c_dialog.getColor(initial=new_color)
  7947. if plot_fill_color.isValid() is False:
  7948. return
  7949. new_color = str(plot_fill_color.name()) + alpha_level
  7950. if act_name == _("Default"):
  7951. for sel_obj in sel_obj_list:
  7952. if sel_obj.kind == 'excellon':
  7953. new_color = self.defaults['excellon_plot_fill']
  7954. new_line_color = self.defaults['excellon_plot_line']
  7955. elif sel_obj.kind == 'gerber':
  7956. new_color = self.defaults['gerber_plot_fill']
  7957. new_line_color = self.defaults['gerber_plot_line']
  7958. elif sel_obj.kind == 'geometry':
  7959. new_color = self.defaults['geometry_plot_line']
  7960. new_line_color = self.defaults['geometry_plot_line']
  7961. else:
  7962. log.debug(
  7963. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7964. continue
  7965. sel_obj.fill_color = new_color
  7966. sel_obj.outline_color = new_line_color
  7967. sel_obj.shapes.redraw(
  7968. update_colors=(new_color, new_line_color)
  7969. )
  7970. return
  7971. if act_name == _("Opacity"):
  7972. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7973. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7974. if ok_button:
  7975. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7976. for sel_obj in sel_obj_list:
  7977. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7978. sel_obj.shapes.redraw(
  7979. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7980. )
  7981. return
  7982. new_line_color = color_variant(new_color[:7], 0.7)
  7983. if act_name == _("White"):
  7984. new_line_color = color_variant("#dedede", 0.7)
  7985. for sel_obj in sel_obj_list:
  7986. sel_obj.fill_color = new_color
  7987. sel_obj.outline_color = new_line_color
  7988. sel_obj.shapes.redraw(
  7989. update_colors=(new_color, new_line_color)
  7990. )
  7991. def generate_cnc_job(self, objects):
  7992. """
  7993. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7994. :param objects: Selected objects in the Project Tab
  7995. :return:
  7996. """
  7997. self.defaults.report_usage("generate_cnc_job()")
  7998. # for obj in objects:
  7999. # obj.generatecncjob()
  8000. for obj in objects:
  8001. obj.on_generatecnc_button_click()
  8002. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8003. """
  8004. Saves the current project to the specified file.
  8005. :param filename: Name of the file in which to save.
  8006. :type filename: str
  8007. :param quit_action: if the project saving will be followed by an app quit; boolean
  8008. :param silent: if True will not display status messages
  8009. :param from_tcl True is run from Tcl Shell
  8010. :return: None
  8011. """
  8012. self.log.debug("save_project()")
  8013. self.save_in_progress = True
  8014. with self.proc_container.new(_("Saving FlatCAM Project")):
  8015. # Capture the latest changes
  8016. # Current object
  8017. try:
  8018. current_object = self.collection.get_active()
  8019. if current_object:
  8020. current_object.read_form()
  8021. except Exception as e:
  8022. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8023. pass
  8024. # Serialize the whole project
  8025. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8026. "options": self.options,
  8027. "version": self.version}
  8028. if self.defaults["global_save_compressed"] is True:
  8029. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8030. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8031. # # Write
  8032. f.write(g)
  8033. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8034. else:
  8035. # Open file
  8036. try:
  8037. f = open(filename, 'w')
  8038. except IOError:
  8039. App.log.error("Failed to open file for saving: %s", filename)
  8040. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8041. return
  8042. # Write
  8043. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8044. f.close()
  8045. # verification of the saved project
  8046. # Open and parse
  8047. try:
  8048. saved_f = open(filename, 'r')
  8049. except IOError:
  8050. if silent is False:
  8051. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8052. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8053. return
  8054. try:
  8055. saved_d = json.load(saved_f, object_hook=dict2obj)
  8056. except Exception:
  8057. if silent is False:
  8058. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8059. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8060. f.close()
  8061. return
  8062. saved_f.close()
  8063. if silent is False:
  8064. if 'version' in saved_d:
  8065. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8066. else:
  8067. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8068. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8069. tb_settings = QSettings("Open Source", "FlatCAM")
  8070. lock_state = self.ui.lock_action.isChecked()
  8071. tb_settings.setValue('toolbar_lock', lock_state)
  8072. # This will write the setting to the platform specific storage.
  8073. del tb_settings
  8074. # if quit:
  8075. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8076. # t.start()
  8077. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8078. def start_delayed_quit(self, delay, filename, should_quit=None):
  8079. """
  8080. :param delay: period of checking if project file size is more than zero; in seconds
  8081. :param filename: the name of the project file to be checked periodically for size more than zero
  8082. :param should_quit: if the task finished will be followed by an app quit; boolean
  8083. :return:
  8084. """
  8085. to_quit = should_quit
  8086. self.save_timer = QtCore.QTimer()
  8087. self.save_timer.setInterval(delay)
  8088. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8089. self.save_timer.start()
  8090. def check_project_file_size(self, filename, should_quit=None):
  8091. """
  8092. :param filename: the name of the project file to be checked periodically for size more than zero
  8093. :param should_quit: will quit the app if True; boolean
  8094. :return:
  8095. """
  8096. try:
  8097. if os.stat(filename).st_size > 0:
  8098. self.save_in_progress = False
  8099. self.save_timer.stop()
  8100. if should_quit:
  8101. self.app_quit.emit()
  8102. except Exception:
  8103. traceback.print_exc()
  8104. def save_project_auto(self):
  8105. """
  8106. Called periodically to save the project.
  8107. 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
  8108. # progress.
  8109. :return:
  8110. """
  8111. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8112. self.on_file_saveproject()
  8113. def save_project_auto_update(self):
  8114. """
  8115. Update the auto save time interval value.
  8116. :return:
  8117. """
  8118. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8119. try:
  8120. if self.autosave_timer.isActive():
  8121. self.autosave_timer.stop()
  8122. except Exception:
  8123. pass
  8124. if self.defaults['global_autosave'] is True:
  8125. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8126. self.autosave_timer.start()
  8127. def on_options_app2project(self):
  8128. """
  8129. Callback for Options->Transfer Options->App=>Project. Copies options
  8130. from application defaults to project defaults.
  8131. :return: None
  8132. """
  8133. self.defaults.report_usage("on_options_app2project")
  8134. self.preferencesUiManager.defaults_read_form()
  8135. self.options.update(self.defaults)
  8136. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8137. """
  8138. Shows a message on the FlatCAM Shell
  8139. :param msg: Message to display.
  8140. :param show: Opens the shell.
  8141. :param error: Shows the message as an error.
  8142. :param warning: Shows the message as an warning.
  8143. :param success: Shows the message as an success.
  8144. :param selected: Indicate that something was selected on canvas
  8145. :return: None
  8146. """
  8147. if show:
  8148. self.ui.shell_dock.show()
  8149. try:
  8150. if error:
  8151. self.shell.append_error(msg + "\n")
  8152. elif warning:
  8153. self.shell.append_warning(msg + "\n")
  8154. elif success:
  8155. self.shell.append_success(msg + "\n")
  8156. elif selected:
  8157. self.shell.append_selected(msg + "\n")
  8158. else:
  8159. self.shell.append_output(msg + "\n")
  8160. except AttributeError:
  8161. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8162. class ArgsThread(QtCore.QObject):
  8163. open_signal = pyqtSignal(list)
  8164. start = pyqtSignal()
  8165. stop = pyqtSignal()
  8166. if sys.platform == 'win32':
  8167. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8168. else:
  8169. address = ('/tmp/testipc', 'AF_UNIX')
  8170. def __init__(self):
  8171. super(ArgsThread, self).__init__()
  8172. self.listener = None
  8173. self.thread_exit = False
  8174. self.start.connect(self.run)
  8175. self.stop.connect(self.close_listener)
  8176. def my_loop(self, address):
  8177. try:
  8178. self.listener = Listener(*address)
  8179. while self.thread_exit is False:
  8180. conn = self.listener.accept()
  8181. self.serve(conn)
  8182. except socket.error:
  8183. try:
  8184. conn = Client(*address)
  8185. conn.send(sys.argv)
  8186. conn.send('close')
  8187. # close the current instance only if there are args
  8188. if len(sys.argv) > 1:
  8189. try:
  8190. self.listener.close()
  8191. except Exception:
  8192. pass
  8193. sys.exit()
  8194. except ConnectionRefusedError:
  8195. if sys.platform == 'win32':
  8196. pass
  8197. else:
  8198. os.system('rm /tmp/testipc')
  8199. self.listener = Listener(*address)
  8200. while True:
  8201. conn = self.listener.accept()
  8202. self.serve(conn)
  8203. def serve(self, conn):
  8204. while self.thread_exit is False:
  8205. msg = conn.recv()
  8206. if msg == 'close':
  8207. break
  8208. self.open_signal.emit(msg)
  8209. conn.close()
  8210. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8211. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8212. @pyqtSlot()
  8213. def run(self):
  8214. self.my_loop(self.address)
  8215. @pyqtSlot()
  8216. def close_listener(self):
  8217. self.thread_exit = True
  8218. self.listener.close()
  8219. # end of file