FlatCAMApp.py 297 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105
  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. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.910
  83. version_date = "2019/02/23"
  84. beta = True
  85. # current date now
  86. date = str(datetime.today()).rpartition(' ')[0]
  87. # URL for update checks and statistics
  88. version_url = "http://flatcam.org/version"
  89. # App URL
  90. app_url = "http://flatcam.org"
  91. # Manual URL
  92. manual_url = "http://flatcam.org/manual/index.html"
  93. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  94. should_we_quit = True
  95. # this variable will hold the project status
  96. # if True it will mean that the project was modified and not saved
  97. should_we_save = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. # General purpose background task
  106. worker_task = QtCore.pyqtSignal(dict)
  107. # File opened
  108. # Handled by:
  109. # * register_folder()
  110. # * register_recent()
  111. # Note: Setting the parameters to unicode does not seem
  112. # to have an effect. Then are received as Qstring
  113. # anyway.
  114. # File type and filename
  115. file_opened = QtCore.pyqtSignal(str, str)
  116. # File type and filename
  117. file_saved = QtCore.pyqtSignal(str, str)
  118. # Percentage of progress
  119. progress = QtCore.pyqtSignal(int)
  120. plots_updated = QtCore.pyqtSignal()
  121. # Emitted by new_object() and passes the new object as argument, plot flag.
  122. # on_object_created() adds the object to the collection, plots on appropriate flag
  123. # and emits new_object_available.
  124. object_created = QtCore.pyqtSignal(object, bool, bool)
  125. # Emitted when a object has been changed (like scaled, mirrored)
  126. object_changed = QtCore.pyqtSignal(object)
  127. # Emitted after object has been plotted.
  128. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  129. object_plotted = QtCore.pyqtSignal(object)
  130. # Emitted when a new object has been added to the collection
  131. # and is ready to be used.
  132. new_object_available = QtCore.pyqtSignal(object)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. ###################
  149. ### OS-specific ###
  150. ###################
  151. # Folder for user settings.
  152. if sys.platform == 'win32':
  153. from win32com.shell import shell, shellcon
  154. if platform.architecture()[0] == '32bit':
  155. App.log.debug("Win32!")
  156. else:
  157. App.log.debug("Win64!")
  158. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  159. '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + \
  163. '/.FlatCAM'
  164. self.os = 'unix'
  165. ###############################
  166. ### Setup folders and files ###
  167. ###############################
  168. if not os.path.exists(self.data_path):
  169. os.makedirs(self.data_path)
  170. App.log.debug('Created data folder: ' + self.data_path)
  171. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  172. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  173. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  174. if not os.path.exists(self.postprocessorpaths):
  175. os.makedirs(self.postprocessorpaths)
  176. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  177. # create current_defaults.FlatConfig file if there is none
  178. try:
  179. f = open(self.data_path + '/current_defaults.FlatConfig')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty current_defaults.FlatConfig')
  183. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. # create factory_defaults.FlatConfig file if there is none
  187. try:
  188. f = open(self.data_path + '/factory_defaults.FlatConfig')
  189. f.close()
  190. except IOError:
  191. App.log.debug('Creating empty factory_defaults.FlatConfig')
  192. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  193. json.dump({}, f)
  194. f.close()
  195. try:
  196. f = open(self.data_path + '/recent.json')
  197. f.close()
  198. except IOError:
  199. App.log.debug('Creating empty recent.json')
  200. f = open(self.data_path + '/recent.json', 'w')
  201. json.dump([], f)
  202. f.close()
  203. # Application directory. CHDIR to it. Otherwise, trying to load
  204. # GUI icons will fail as their path is relative.
  205. # This will fail under cx_freeze ...
  206. self.app_home = os.path.dirname(os.path.realpath(__file__))
  207. App.log.debug("Application path is " + self.app_home)
  208. App.log.debug("Started in " + os.getcwd())
  209. # cx_freeze workaround
  210. if os.path.isfile(self.app_home):
  211. self.app_home = os.path.dirname(self.app_home)
  212. os.chdir(self.app_home)
  213. # Create multiprocessing pool
  214. self.pool = Pool()
  215. # variable to store mouse coordinates
  216. self.mouse = [0, 0]
  217. ####################
  218. ## Initialize GUI ##
  219. ####################
  220. # FlatCAM colors used in plotting
  221. self.FC_light_green = '#BBF268BF'
  222. self.FC_dark_green = '#006E20BF'
  223. self.FC_light_blue = '#a5a5ffbf'
  224. self.FC_dark_blue = '#0000ffbf'
  225. QtCore.QObject.__init__(self)
  226. self.ui = FlatCAMGUI(self.version, self.beta, self)
  227. # self.connect(self.ui,
  228. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  229. # self.save_geometry) PyQt4
  230. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  231. self.ui.final_save.connect(self.final_save)
  232. ##############
  233. #### Data ####
  234. ##############
  235. self.recent = []
  236. self.clipboard = QtWidgets.QApplication.clipboard()
  237. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  238. self.project_filename = None
  239. self.toggle_units_ignore = False
  240. # self.defaults_form = PreferencesUI()
  241. self.general_defaults_form = GeneralPreferencesUI()
  242. self.gerber_defaults_form = GerberPreferencesUI()
  243. self.excellon_defaults_form = ExcellonPreferencesUI()
  244. self.geometry_defaults_form = GeometryPreferencesUI()
  245. self.cncjob_defaults_form = CNCJobPreferencesUI()
  246. self.tools_defaults_form = ToolsPreferencesUI()
  247. # when adding entries here read the comments in the method found bellow named:
  248. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  249. self.defaults_form_fields = {
  250. "units": self.general_defaults_form.general_app_group.units_radio,
  251. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  252. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  253. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  254. "global_project_at_startup": self.general_defaults_form.general_app_group.project_startup_cb,
  255. "global_project_autohide": self.general_defaults_form.general_app_group.project_autohide_cb,
  256. "global_advanced": self.general_defaults_form.general_app_group.advanced_cb,
  257. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  258. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  259. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  260. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  261. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  262. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  263. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  264. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  265. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  266. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  267. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  268. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  269. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  270. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  271. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  272. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  273. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  274. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  275. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  276. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  277. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  278. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  279. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  280. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  281. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  282. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  283. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  284. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  285. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  286. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  287. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  288. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  289. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  290. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  291. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  292. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  293. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  294. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  295. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  296. "excellon_offset": self.excellon_defaults_form.excellon_gen_group.offset_entry,
  297. "excellon_toolchangexy": self.excellon_defaults_form.excellon_gen_group.toolchangexy_entry,
  298. "excellon_startz": self.excellon_defaults_form.excellon_gen_group.estartz_entry,
  299. "excellon_endz": self.excellon_defaults_form.excellon_gen_group.eendz_entry,
  300. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_gen_group.feedrate_rapid_entry,
  301. "excellon_z_pdepth": self.excellon_defaults_form.excellon_gen_group.pdepth_entry,
  302. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_gen_group.feedrate_probe_entry,
  303. "excellon_f_plunge": self.excellon_defaults_form.excellon_gen_group.fplunge_cb,
  304. "excellon_f_retract": self.excellon_defaults_form.excellon_gen_group.fretract_cb,
  305. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  306. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  307. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  308. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  309. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  310. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  311. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  312. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  313. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  314. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  315. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  316. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  317. "excellon_exp_units": self.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  318. "excellon_exp_format": self.excellon_defaults_form.excellon_exp_group.format_radio,
  319. "excellon_exp_integer": self.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  320. "excellon_exp_decimals": self.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  321. "excellon_exp_zeros": self.excellon_defaults_form.excellon_exp_group.zeros_radio,
  322. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  323. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  324. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  325. "geometry_segx": self.geometry_defaults_form.geometry_gen_group.segx_entry,
  326. "geometry_segy": self.geometry_defaults_form.geometry_gen_group.segy_entry,
  327. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_gen_group.cncfeedrate_rapid_entry,
  328. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_gen_group.feedrate_probe_entry,
  329. "geometry_z_pdepth": self.geometry_defaults_form.geometry_gen_group.pdepth_entry,
  330. "geometry_f_plunge": self.geometry_defaults_form.geometry_gen_group.fplunge_cb,
  331. "geometry_toolchangexy": self.geometry_defaults_form.geometry_gen_group.toolchangexy_entry,
  332. "geometry_startz": self.geometry_defaults_form.geometry_gen_group.gstartz_entry,
  333. "geometry_endz": self.geometry_defaults_form.geometry_gen_group.gendz_entry,
  334. "geometry_extracut": self.geometry_defaults_form.geometry_gen_group.extracut_cb,
  335. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  336. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  337. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  338. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  339. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  340. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  341. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  342. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  343. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  344. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  345. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  346. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  347. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  348. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  349. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  350. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  351. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  352. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  353. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  354. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  355. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  356. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  357. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  358. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  359. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  360. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  361. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  362. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  363. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  364. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  365. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  366. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  367. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  368. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  369. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  370. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  371. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  372. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  373. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  374. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  375. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  376. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  377. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  378. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  379. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  380. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  381. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  382. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  383. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  384. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  385. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  386. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  387. "tools_panelize_panel_type": self.tools_defaults_form.tools_panelize_group.panel_type_radio,
  388. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  389. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  390. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  391. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  392. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  393. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  394. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry,
  395. "tools_transform_rotate": self.tools_defaults_form.tools_transform_group.rotate_entry,
  396. "tools_transform_skew_x": self.tools_defaults_form.tools_transform_group.skewx_entry,
  397. "tools_transform_skew_y": self.tools_defaults_form.tools_transform_group.skewy_entry,
  398. "tools_transform_scale_x": self.tools_defaults_form.tools_transform_group.scalex_entry,
  399. "tools_transform_scale_y": self.tools_defaults_form.tools_transform_group.scaley_entry,
  400. "tools_transform_scale_link": self.tools_defaults_form.tools_transform_group.link_cb,
  401. "tools_transform_scale_reference": self.tools_defaults_form.tools_transform_group.reference_cb,
  402. "tools_transform_offset_x": self.tools_defaults_form.tools_transform_group.offx_entry,
  403. "tools_transform_offset_y": self.tools_defaults_form.tools_transform_group.offy_entry,
  404. "tools_transform_mirror_reference": self.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  405. "tools_transform_mirror_point": self.tools_defaults_form.tools_transform_group.flip_ref_entry
  406. }
  407. # loads postprocessors
  408. self.postprocessors = load_postprocessors(self)
  409. for name in list(self.postprocessors.keys()):
  410. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  411. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  412. if name == 'hpgl':
  413. continue
  414. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  415. self.defaults = LoudDict()
  416. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  417. self.defaults.update({
  418. "global_serial": 0,
  419. "global_stats": {},
  420. "units": "IN",
  421. "global_version_check": True,
  422. "global_send_stats": True,
  423. "global_project_at_startup": False,
  424. "global_project_autohide": True,
  425. "global_advanced": False,
  426. "global_gridx": 1.0,
  427. "global_gridy": 1.0,
  428. "global_snap_max": 0.05,
  429. "global_grid_context_menu": {
  430. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  431. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  432. },
  433. "global_plot_fill": '#BBF268BF',
  434. "global_plot_line": '#006E20BF',
  435. "global_sel_fill": '#a5a5ffbf',
  436. "global_sel_line": '#0000ffbf',
  437. "global_alt_sel_fill": '#BBF268BF',
  438. "global_alt_sel_line": '#006E20BF',
  439. "global_draw_color": '#FF0000',
  440. "global_sel_draw_color": '#0000FF',
  441. "global_pan_button": '2',
  442. "global_mselect_key": 'Control',
  443. # "global_pan_with_space_key": False,
  444. "global_workspace": False,
  445. "global_workspaceT": "A4P",
  446. "global_toolbar_view": 127,
  447. "global_background_timeout": 300000, # Default value is 5 minutes
  448. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  449. # (python trace only for unknown errors),
  450. # 1 = show trace(show trace allways),
  451. # 2 = (For the future).
  452. # Persistence
  453. "global_last_folder": None,
  454. "global_last_save_folder": None,
  455. # Default window geometry
  456. "global_def_win_x": 100,
  457. "global_def_win_y": 100,
  458. "global_def_win_w": 1024,
  459. "global_def_win_h": 650,
  460. # Constants...
  461. "global_defaults_save_period_ms": 20000, # Time between default saves.
  462. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  463. "global_shell_at_startup": False, # Show the shell at startup.
  464. "global_recent_limit": 10, # Max. items in recent list.
  465. "fit_key": 'V',
  466. "zoom_out_key": '-',
  467. "zoom_in_key": '=',
  468. "grid_toggle_key": 'G',
  469. "zoom_ratio": 1.5,
  470. "global_point_clipboard_format": "(%.4f, %.4f)",
  471. "global_zdownrate": None,
  472. "gerber_plot": True,
  473. "gerber_solid": True,
  474. "gerber_multicolored": False,
  475. "gerber_isotooldia": 0.016,
  476. "gerber_isopasses": 1,
  477. "gerber_isooverlap": 0.15,
  478. "gerber_combine_passes": False,
  479. "gerber_milling_type": "cl",
  480. "gerber_noncoppermargin": 0.1,
  481. "gerber_noncopperrounded": False,
  482. "gerber_bboxmargin": 0.1,
  483. "gerber_bboxrounded": False,
  484. "gerber_circle_steps": 64,
  485. "gerber_use_buffer_for_union": True,
  486. "excellon_plot": True,
  487. "excellon_solid": True,
  488. "excellon_format_upper_in": 2,
  489. "excellon_format_lower_in": 4,
  490. "excellon_format_upper_mm": 3,
  491. "excellon_format_lower_mm": 3,
  492. "excellon_zeros": "L",
  493. "excellon_units": "INCH",
  494. "excellon_optimization_type": 'B',
  495. "excellon_search_time": 3,
  496. "excellon_drillz": -0.1,
  497. "excellon_travelz": 0.1,
  498. "excellon_feedrate": 3.0,
  499. "excellon_feedrate_rapid": 3.0,
  500. "excellon_feedrate_probe": 3.0,
  501. "excellon_spindlespeed": None,
  502. "excellon_dwell": False,
  503. "excellon_dwelltime": 1,
  504. "excellon_toolchange": False,
  505. "excellon_toolchangez": 1.0,
  506. "excellon_toolchangexy": "0.0, 0.0",
  507. "excellon_tooldia": 0.016,
  508. "excellon_offset": 0.0,
  509. "excellon_slot_tooldia": 0.016,
  510. "excellon_startz": None,
  511. "excellon_endz": 2.0,
  512. "excellon_ppname_e": 'default',
  513. "excellon_z_pdepth": -0.02,
  514. "excellon_f_plunge": False,
  515. "excellon_f_retract": False,
  516. "excellon_gcode_type": "drills",
  517. "excellon_exp_units": 'INCH',
  518. "excellon_exp_format": 'ndec',
  519. "excellon_exp_integer": 2,
  520. "excellon_exp_decimals": 4,
  521. "excellon_exp_zeros": 'LZ',
  522. "geometry_plot": True,
  523. "geometry_segx": 0.0,
  524. "geometry_segy": 0.0,
  525. "geometry_cutz": -0.002,
  526. "geometry_travelz": 0.1,
  527. "geometry_toolchange": False,
  528. "geometry_toolchangez": 1.0,
  529. "geometry_toolchangexy": "0.0, 0.0",
  530. "geometry_startz": None,
  531. "geometry_endz": 2.0,
  532. "geometry_feedrate": 3.0,
  533. "geometry_feedrate_z": 3.0,
  534. "geometry_feedrate_rapid": 3.0,
  535. "geometry_feedrate_probe": 3.0,
  536. "geometry_cnctooldia": 0.016,
  537. "geometry_spindlespeed": None,
  538. "geometry_dwell": False,
  539. "geometry_dwelltime": 1,
  540. "geometry_ppname_g": 'default',
  541. "geometry_z_pdepth": -0.02,
  542. "geometry_f_plunge": False,
  543. "geometry_depthperpass": 0.002,
  544. "geometry_multidepth": False,
  545. "geometry_extracut": False,
  546. "geometry_circle_steps": 64,
  547. "cncjob_plot": True,
  548. "cncjob_plot_kind": 'all',
  549. "cncjob_tooldia": 0.0393701,
  550. "cncjob_coords_decimals": 4,
  551. "cncjob_fr_decimals": 2,
  552. "cncjob_prepend": "",
  553. "cncjob_append": "",
  554. "cncjob_steps_per_circle": 64,
  555. "tools_ncctools": "1.0, 0.5",
  556. "tools_nccoverlap": 0.4,
  557. "tools_nccmargin": 0.1,
  558. "tools_nccmethod": "seed",
  559. "tools_nccconnect": True,
  560. "tools_ncccontour": True,
  561. "tools_nccrest": False,
  562. "tools_cutouttooldia": 0.1,
  563. "tools_cutoutmargin": 0.1,
  564. "tools_cutoutgapsize": 0.15,
  565. "tools_gaps_rect": "4",
  566. "tools_gaps_ff": "8",
  567. "tools_painttooldia": 0.07,
  568. "tools_paintoverlap": 0.15,
  569. "tools_paintmargin": 0.0,
  570. "tools_paintmethod": "seed",
  571. "tools_selectmethod": "single",
  572. "tools_pathconnect": True,
  573. "tools_paintcontour": True,
  574. "tools_2sided_mirror_axis": "X",
  575. "tools_2sided_axis_loc": "point",
  576. "tools_2sided_drilldia": 1,
  577. "tools_film_type": 'neg',
  578. "tools_film_boundary": 1,
  579. "tools_film_scale": 0,
  580. "tools_panelize_spacing_columns": 0,
  581. "tools_panelize_spacing_rows": 0,
  582. "tools_panelize_columns": 1,
  583. "tools_panelize_rows": 1,
  584. "tools_panelize_constrain": False,
  585. "tools_panelize_constrainx": 0.0,
  586. "tools_panelize_constrainy": 0.0,
  587. "tools_panelize_panel_type": 'gerber',
  588. "tools_calc_vshape_tip_dia": 0.007874,
  589. "tools_calc_vshape_tip_angle": 30,
  590. "tools_calc_vshape_cut_z": 0.000787,
  591. "tools_calc_electro_length": 10.0,
  592. "tools_calc_electro_width": 10.0,
  593. "tools_calc_electro_cdensity":13.0,
  594. "tools_calc_electro_growth": 10.0,
  595. "tools_transform_rotate": 90,
  596. "tools_transform_skew_x": 0.0,
  597. "tools_transform_skew_y": 0.0,
  598. "tools_transform_scale_x": 1.0,
  599. "tools_transform_scale_y": 1.0,
  600. "tools_transform_scale_link": True,
  601. "tools_transform_scale_reference": True,
  602. "tools_transform_offset_x": 0.0,
  603. "tools_transform_offset_y": 0.0,
  604. "tools_transform_mirror_reference": False,
  605. "tools_transform_mirror_point": (0, 0)
  606. })
  607. ###############################
  608. ### Load defaults from file ###
  609. if user_defaults:
  610. self.load_defaults(filename='current_defaults')
  611. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  612. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  613. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  614. self.save_defaults(silent=True)
  615. self.propagate_defaults(silent=True)
  616. self.restore_main_win_geom()
  617. def auto_save_defaults():
  618. try:
  619. self.save_defaults(silent=True)
  620. self.propagate_defaults(silent=True)
  621. finally:
  622. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  623. # the following lines activates automatic defaults save
  624. # if user_defaults:
  625. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  626. # self.options_form = PreferencesUI()
  627. self.general_options_form = GeneralPreferencesUI()
  628. self.gerber_options_form = GerberPreferencesUI()
  629. self.excellon_options_form = ExcellonPreferencesUI()
  630. self.geometry_options_form = GeometryPreferencesUI()
  631. self.cncjob_options_form = CNCJobPreferencesUI()
  632. self.tools_options_form = ToolsPreferencesUI()
  633. self.options_form_fields = {
  634. "units": self.general_options_form.general_app_group.units_radio,
  635. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  636. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  637. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  638. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  639. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  640. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  641. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  642. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  643. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  644. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  645. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  646. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  647. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  648. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  649. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  650. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  651. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  652. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  653. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  654. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  655. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  656. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  657. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  658. "excellon_feedrate_rapid": self.excellon_options_form.excellon_gen_group.feedrate_rapid_entry,
  659. "excellon_toolchangexy": self.excellon_options_form.excellon_gen_group.toolchangexy_entry,
  660. "excellon_f_plunge": self.excellon_options_form.excellon_gen_group.fplunge_cb,
  661. "excellon_startz": self.excellon_options_form.excellon_gen_group.estartz_entry,
  662. "excellon_endz": self.excellon_options_form.excellon_gen_group.eendz_entry,
  663. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  664. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  665. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  666. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  667. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  668. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  669. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  670. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  671. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  672. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  673. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  674. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  675. "geometry_segx": self.geometry_options_form.geometry_gen_group.segx_entry,
  676. "geometry_segy": self.geometry_options_form.geometry_gen_group.segy_entry,
  677. "geometry_feedrate_rapid": self.geometry_options_form.geometry_gen_group.cncfeedrate_rapid_entry,
  678. "geometry_f_plunge": self.geometry_options_form.geometry_gen_group.fplunge_cb,
  679. "geometry_toolchangexy": self.geometry_options_form.geometry_gen_group.toolchangexy_entry,
  680. "geometry_startz": self.geometry_options_form.geometry_gen_group.gstartz_entry,
  681. "geometry_endz": self.geometry_options_form.geometry_gen_group.gendz_entry,
  682. "geometry_extracut": self.geometry_options_form.geometry_gen_group.extracut_cb,
  683. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  684. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  685. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  686. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  687. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  688. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  689. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  690. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  691. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  692. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  693. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  694. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  695. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  696. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  697. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  698. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  699. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  700. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  701. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  702. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  703. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  704. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  705. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  706. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  707. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  708. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  709. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  710. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  711. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  712. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  713. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  714. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  715. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  716. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  717. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  718. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  719. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  720. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  721. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  722. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  723. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  724. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  725. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  726. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  727. }
  728. for name in list(self.postprocessors.keys()):
  729. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  730. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  731. self.options = LoudDict()
  732. self.options.set_change_callback(self.on_options_dict_change)
  733. self.options.update({
  734. "units": "IN",
  735. "global_gridx": 1.0,
  736. "global_gridy": 1.0,
  737. "global_snap_max": 0.05,
  738. "global_background_timeout": 300000, # Default value is 5 minutes
  739. "global_verbose_error_level": 0, # Shell verbosity:
  740. # 0 = default(python trace only for unknown errors),
  741. # 1 = show trace(show trace allways), 2 = (For the future).
  742. "gerber_plot": True,
  743. "gerber_solid": True,
  744. "gerber_multicolored": False,
  745. "gerber_isotooldia": 0.016,
  746. "gerber_isopasses": 1,
  747. "gerber_isooverlap": 0.15,
  748. "gerber_combine_passes": True,
  749. "gerber_noncoppermargin": 0.0,
  750. "gerber_noncopperrounded": False,
  751. "gerber_bboxmargin": 0.0,
  752. "gerber_bboxrounded": False,
  753. "excellon_plot": True,
  754. "excellon_solid": False,
  755. "excellon_format_upper_in": 2,
  756. "excellon_format_lower_in": 4,
  757. "excellon_format_upper_mm": 3,
  758. "excellon_format_lower_mm": 3,
  759. "excellon_units": 'INCH',
  760. "excellon_optimization_type": 'B',
  761. "excellon_search_time": 3,
  762. "excellon_zeros": "L",
  763. "excellon_drillz": -0.1,
  764. "excellon_travelz": 0.1,
  765. "excellon_feedrate": 3.0,
  766. "excellon_feedrate_rapid": 3.0,
  767. "excellon_spindlespeed": None,
  768. "excellon_dwell": True,
  769. "excellon_dwelltime": 1000,
  770. "excellon_toolchange": False,
  771. "excellon_toolchangez": 1.0,
  772. "excellon_toolchangexy": "0.0, 0.0",
  773. "excellon_tooldia": 0.016,
  774. "excellon_ppname_e": 'default',
  775. "excellon_f_plunge": False,
  776. "excellon_startz": None,
  777. "excellon_endz": 2.0,
  778. "geometry_plot": True,
  779. "geometry_segx": 0.0,
  780. "geometry_segy": 0.0,
  781. "geometry_cutz": -0.002,
  782. "geometry_travelz": 0.1,
  783. "geometry_feedrate": 3.0,
  784. "geometry_feedrate_z": 3.0,
  785. "geometry_feedrate_rapid": 3.0,
  786. "geometry_spindlespeed": None,
  787. "geometry_dwell": True,
  788. "geometry_dwelltime": 1000,
  789. "geometry_cnctooldia": 0.016,
  790. "geometry_toolchange": False,
  791. "geometry_toolchangez": 2.0,
  792. "geometry_toolchangexy": "0.0, 0.0",
  793. "geometry_startz": None,
  794. "geometry_endz": 2.0,
  795. "geometry_ppname_g": "default",
  796. "geometry_f_plunge": False,
  797. "geometry_depthperpass": 0.002,
  798. "geometry_multidepth": False,
  799. "geometry_extracut": False,
  800. "cncjob_plot": True,
  801. "cncjob_tooldia": 0.016,
  802. "cncjob_prepend": "",
  803. "cncjob_append": "",
  804. "tools_ncctools": "1.0, 0.5",
  805. "tools_nccoverlap": 0.4,
  806. "tools_nccmargin": 1,
  807. "tools_cutouttooldia": 0.07,
  808. "tools_cutoutmargin": 0.1,
  809. "tools_cutoutgapsize": 0.15,
  810. "tools_gaps_rect": "4",
  811. "tools_gaps_ff": "8",
  812. "tools_painttooldia": 0.07,
  813. "tools_paintoverlap": 0.15,
  814. "tools_paintmargin": 0.0,
  815. "tools_paintmethod": "seed",
  816. "tools_selectmethod": "single",
  817. "tools_pathconnect": True,
  818. "tools_paintcontour": True,
  819. "tools_2sided_mirror_axis": "X",
  820. "tools_2sided_axis_loc": 'point',
  821. "tools_2sided_drilldia": 1,
  822. "tools_film_type": 'neg',
  823. "tools_film_boundary": 1,
  824. "tools_film_scale": 0,
  825. "tools_panelize_spacing_columns": 0,
  826. "tools_panelize_spacing_rows": 0,
  827. "tools_panelize_columns": 1,
  828. "tools_panelize_rows": 1,
  829. "tools_panelize_constrain": False,
  830. "tools_panelize_constrainx": 0.0,
  831. "tools_panelize_constrainy": 0.0
  832. })
  833. self.options.update(self.defaults) # Copy app defaults to project options
  834. self.gen_form = None
  835. self.ger_form = None
  836. self.exc_form = None
  837. self.geo_form = None
  838. self.cnc_form = None
  839. self.tools_form = None
  840. self.on_options_combo_change(0) # Will show the initial form
  841. ### Define OBJECT COLLECTION ###
  842. self.collection = ObjectCollection(self)
  843. self.ui.project_tab_layout.addWidget(self.collection.view)
  844. ###
  845. self.log.debug("Finished creating Object Collection.")
  846. ### Initialize the color box's color in Preferences -> Global -> Color
  847. # Init Plot Colors
  848. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  849. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  850. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  851. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  852. int(self.defaults['global_plot_fill'][7:9], 16))
  853. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  854. int(self.defaults['global_plot_fill'][7:9], 16))
  855. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  856. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  857. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  858. # Init Left-Right Selection colors
  859. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  860. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  861. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  862. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  863. int(self.defaults['global_sel_fill'][7:9], 16))
  864. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  865. int(self.defaults['global_sel_fill'][7:9], 16))
  866. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  867. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  868. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  869. # Init Right-Left Selection colors
  870. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  871. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  872. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  873. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  874. int(self.defaults['global_sel_fill'][7:9], 16))
  875. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  876. int(self.defaults['global_sel_fill'][7:9], 16))
  877. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  878. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  879. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  880. # Init Draw color and Selection Draw Color
  881. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  882. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  883. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  884. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  885. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  886. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  887. #### End of Data ####
  888. #### Plot Area ####
  889. start_plot_time = time.time() # debug
  890. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  891. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  892. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  893. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  894. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  895. # Keys over plot enabled
  896. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  897. self.ui.splitter.setStretchFactor(1, 2)
  898. # So it can receive key presses
  899. self.plotcanvas.vispy_canvas.native.setFocus()
  900. self.app_cursor = self.plotcanvas.new_cursor()
  901. self.app_cursor.enabled = False
  902. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  903. # depending on from where those tools are called different actions can be done
  904. self.call_source = 'app'
  905. end_plot_time = time.time()
  906. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  907. ### EDITOR section
  908. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  909. self.exc_editor = FlatCAMExcEditor(self)
  910. #### Adjust tabs width ####
  911. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  912. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  913. self.collection.view.setMinimumWidth(290)
  914. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  915. #### Worker ####
  916. self.workers = WorkerStack()
  917. self.worker_task.connect(self.workers.add_task)
  918. ### Signal handling ###
  919. ## Custom signals
  920. self.inform.connect(self.info)
  921. self.message.connect(self.message_dialog)
  922. self.progress.connect(self.set_progress_bar)
  923. self.object_created.connect(self.on_object_created)
  924. self.object_changed.connect(self.on_object_changed)
  925. self.object_plotted.connect(self.on_object_plotted)
  926. self.plots_updated.connect(self.on_plots_updated)
  927. self.file_opened.connect(self.register_recent)
  928. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  929. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  930. ## Standard signals
  931. # Menu
  932. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  933. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  934. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  935. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  936. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  937. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  938. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  939. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  940. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  941. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  942. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  943. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  944. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  945. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  946. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  947. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  948. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  949. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  950. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  951. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  952. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  953. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  954. self.ui.menueditedit.triggered.connect(self.object2editor)
  955. self.ui.menueditok.triggered.connect(self.editor2object)
  956. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  957. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  958. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  959. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  960. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  961. self.ui.menueditdelete.triggered.connect(self.on_delete)
  962. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  963. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  964. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  965. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  966. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  967. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  968. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  969. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  970. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  971. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  972. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  973. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  974. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  975. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  976. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  977. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  978. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  979. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  980. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  981. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  982. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  983. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  984. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  985. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  986. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  987. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  988. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  989. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  990. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  991. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  992. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  993. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  994. self.ui.menuhelp_about.triggered.connect(self.on_about)
  995. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  996. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  997. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  998. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  999. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1000. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1001. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1002. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1003. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1004. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1005. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1006. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1007. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1008. # Toolbar
  1009. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1010. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1011. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1012. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1013. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1014. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1015. self.ui.replot_btn.triggered.connect(self.plot_all)
  1016. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1017. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1018. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1019. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1020. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1021. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1022. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1023. self.ui.delete_btn.triggered.connect(self.on_delete)
  1024. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1025. # Context Menu
  1026. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1027. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1028. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1029. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1030. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1031. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1032. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1033. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1034. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1035. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1036. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1037. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1038. self.ui.clearplot.triggered.connect(self.clear_plots)
  1039. self.ui.replot.triggered.connect(self.plot_all)
  1040. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1041. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1042. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1043. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1044. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1045. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1046. # Preferences Plot Area TAB
  1047. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1048. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1049. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1050. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1051. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1052. ###############################
  1053. ### GUI PREFERENCES SIGNALS ###
  1054. ###############################
  1055. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1056. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1057. ###############################
  1058. ### GUI PREFERENCES SIGNALS ###
  1059. ###############################
  1060. # Setting plot colors signals
  1061. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1062. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1063. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1064. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1065. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1066. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1067. # Setting selection (left - right) colors signals
  1068. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1069. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1070. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1071. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1072. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1073. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1074. # Setting selection (right - left) colors signals
  1075. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1076. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1077. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1078. self.on_alt_sf_color_spinner)
  1079. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1080. self.on_alt_sf_color_slider)
  1081. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1082. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1083. # Setting Editor Draw colors signals
  1084. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1085. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1086. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1087. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1088. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1089. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1090. self.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1091. # Modify G-CODE Plot Area TAB
  1092. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1093. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1094. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1095. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1096. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1097. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1098. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1099. # Object list
  1100. self.collection.view.activated.connect(self.on_row_activated)
  1101. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1102. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1103. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1104. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1105. self.on_excellon_defaults_button)
  1106. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1107. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1108. self.on_excellon_options_button)
  1109. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1110. self.tool_tab_locked = False
  1111. # decide if to show or hide the Notebook side of the screen at startup
  1112. if self.defaults["global_project_at_startup"] is True:
  1113. self.ui.splitter.setSizes([1, 1])
  1114. else:
  1115. self.ui.splitter.setSizes([0, 1])
  1116. ####################
  1117. ### Other setups ###
  1118. ####################
  1119. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1120. self.setup_obj_classes()
  1121. self.setup_recent_items()
  1122. self.setup_component_editor()
  1123. #############
  1124. ### Shell ###
  1125. #############
  1126. ###
  1127. # Auto-complete KEYWORDS
  1128. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1129. 'aligndrill', 'clear',
  1130. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1131. 'export_gcode',
  1132. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1133. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1134. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1135. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1136. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1137. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1138. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1139. ]
  1140. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1141. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1142. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1143. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1144. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1145. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1146. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1147. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1148. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1149. ]
  1150. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1151. self.shell = FCShell(self, version=self.version)
  1152. self.shell._edit.set_model_data(self.myKeywords)
  1153. self.shell.setWindowIcon(self.ui.app_icon)
  1154. self.shell.setWindowTitle("FlatCAM Shell")
  1155. self.shell.resize(*self.defaults["global_shell_shape"])
  1156. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1157. self.shell.append_output("(Type help to get started)\n\n")
  1158. self.init_tcl()
  1159. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1160. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1161. self.ui.shell_dock.setWidget(self.shell)
  1162. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1163. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1164. QtWidgets.QDockWidget.DockWidgetFloatable |
  1165. QtWidgets.QDockWidget.DockWidgetClosable)
  1166. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1167. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1168. if self.defaults["global_shell_at_startup"]:
  1169. self.ui.shell_dock.show()
  1170. else:
  1171. self.ui.shell_dock.hide()
  1172. #########################
  1173. ### Tools and Plugins ###
  1174. #########################
  1175. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1176. self.install_tools()
  1177. ### System Font Parsing ###
  1178. # self.f_parse = ParseFont(self)
  1179. # self.parse_system_fonts()
  1180. # test if the program was started with a script as parameter
  1181. if self.cmd_line_shellfile:
  1182. try:
  1183. with open(self.cmd_line_shellfile, "r") as myfile:
  1184. cmd_line_shellfile_text = myfile.read()
  1185. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1186. except Exception as ext:
  1187. print("ERROR: ", ext)
  1188. sys.exit(2)
  1189. ###########################
  1190. #### Check for updates ####
  1191. ###########################
  1192. # Separate thread (Not worker)
  1193. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1194. if (self.beta is False or self.beta is None) and \
  1195. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1196. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1197. self.thr2 = QtCore.QThread()
  1198. self.worker_task.emit({'fcn': self.version_check,
  1199. 'params': []})
  1200. self.thr2.start()
  1201. ####################################
  1202. #### Variables for global usage ####
  1203. ####################################
  1204. # coordinates for relative position display
  1205. self.rel_point1 = (0, 0)
  1206. self.rel_point2 = (0, 0)
  1207. # variable to store coordinates
  1208. self.pos = (0, 0)
  1209. self.pos_jump = (0, 0)
  1210. # variable to store if there was motion before right mouse button click (panning)
  1211. self.panning_action = False
  1212. # variable to store if a command is active (then the var is not None) and which one it is
  1213. self.command_active = None
  1214. # variable to store the status of moving selection action
  1215. # None value means that it's not an selection action
  1216. # True value = a selection from left to right
  1217. # False value = a selection from right to left
  1218. self.selection_type = None
  1219. # List to store the objects that are currently loaded in FlatCAM
  1220. # This list is updated on each object creation or object delete
  1221. self.all_objects_list = []
  1222. # List to store the objects that are selected
  1223. self.sel_objects_list = []
  1224. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1225. self.key_modifiers = None
  1226. # Variable to hold the status of the axis
  1227. self.toggle_axis = True
  1228. # Variable to store the status of the fullscreen event
  1229. self.toggle_fscreen = False
  1230. self.cursor = None
  1231. # Variable to store the GCODE that was edited
  1232. self.gcode_edited = ""
  1233. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1234. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1235. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1236. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1237. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1238. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1239. 'mpf']
  1240. self.svg_list = ['svg']
  1241. self.dxf_list = ['dxf']
  1242. self.prj_list = ['flatprj']
  1243. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1244. # flag for polygons not cleared
  1245. self.poly_not_cleared = False
  1246. ### Save defaults to factory_defaults.FlatConfig file ###
  1247. ### It's done only once after install #############
  1248. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1249. fac_def_from_file = factory_file.read()
  1250. factory_defaults = json.loads(fac_def_from_file)
  1251. # if the file contain an empty dictionary then save the factory defaults into the file
  1252. if not factory_defaults:
  1253. self.save_factory_defaults(silent=False)
  1254. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1255. self.on_layout(index=None, lay='compact')
  1256. factory_file.close()
  1257. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1258. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1259. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1260. # Post-GUI initialization: Experimental attempt
  1261. # to perform unit tests on the GUI.
  1262. # if post_gui is not None:
  1263. # post_gui(self)
  1264. App.log.debug("END of constructor. Releasing control.")
  1265. # accept a project file as command line parameter
  1266. # the path/file_name must be enclosed in quotes if it contain spaces
  1267. for argument in App.args:
  1268. if '.FlatPrj' in argument:
  1269. try:
  1270. project_name = str(argument)
  1271. if project_name == "":
  1272. self.inform.emit("Open cancelled.")
  1273. else:
  1274. # self.open_project(project_name)
  1275. run_from_arg = True
  1276. self.worker_task.emit({'fcn': self.open_project,
  1277. 'params': [project_name, run_from_arg]})
  1278. except Exception as e:
  1279. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1280. def defaults_read_form(self):
  1281. for option in self.defaults_form_fields:
  1282. try:
  1283. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1284. except:
  1285. pass
  1286. def defaults_write_form(self):
  1287. for option in self.defaults:
  1288. self.defaults_write_form_field(option)
  1289. # try:
  1290. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1291. # except KeyError:
  1292. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1293. # # TODO: Rethink this?
  1294. # pass
  1295. def defaults_write_form_field(self, field):
  1296. try:
  1297. self.defaults_form_fields[field].set_value(self.defaults[field])
  1298. except KeyError:
  1299. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1300. # TODO: Rethink this?
  1301. pass
  1302. def clear_pool(self):
  1303. self.pool.close()
  1304. self.pool = Pool()
  1305. self.pool_recreated.emit(self.pool)
  1306. gc.collect()
  1307. # the order that the tools are installed is important as they can depend on each other install position
  1308. def install_tools(self):
  1309. self.dblsidedtool = DblSidedTool(self)
  1310. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1311. self.measurement_tool = Measurement(self)
  1312. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1313. self.panelize_tool = Panelize(self)
  1314. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1315. self.film_tool = Film(self)
  1316. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1317. self.move_tool = ToolMove(self)
  1318. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1319. before=self.ui.menueditorigin)
  1320. self.cutout_tool = ToolCutOut(self)
  1321. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1322. before=self.measurement_tool.menuAction)
  1323. self.ncclear_tool = NonCopperClear(self)
  1324. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1325. before=self.measurement_tool.menuAction, separator=True)
  1326. self.paint_tool = ToolPaint(self)
  1327. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1328. before=self.measurement_tool.menuAction, separator=True)
  1329. self.calculator_tool = ToolCalculator(self)
  1330. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1331. self.transform_tool = ToolTransform(self)
  1332. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1333. self.properties_tool = Properties(self)
  1334. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1335. self.image_tool = ToolImage(self)
  1336. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1337. separator=True)
  1338. self.log.debug("Tools are installed.")
  1339. def remove_tools(self):
  1340. for act in self.ui.menutool.actions():
  1341. self.ui.menutool.removeAction(act)
  1342. def init_tools(self):
  1343. log.debug("init_tools()")
  1344. # delete the data currently in the Tools Tab and the Tab itself
  1345. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1346. if widget is not None:
  1347. widget.deleteLater()
  1348. self.ui.notebook.removeTab(2)
  1349. # rebuild the Tools Tab
  1350. self.ui.tool_tab = QtWidgets.QWidget()
  1351. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1352. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1353. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1354. self.ui.tool_scroll_area = VerticalScrollArea()
  1355. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1356. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1357. # first remove all of them
  1358. self.remove_tools()
  1359. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1360. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1361. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1362. # third install all of them
  1363. self.install_tools()
  1364. self.log.debug("Tools are initialized.")
  1365. # def parse_system_fonts(self):
  1366. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1367. # 'params': []})
  1368. def object2editor(self):
  1369. """
  1370. Send the current Geometry or Excellon object (if any) into the editor.
  1371. :return: None
  1372. """
  1373. self.report_usage("object2editor()")
  1374. # adjust the visibility of some of the canvas context menu
  1375. self.ui.popmenu_edit.setVisible(False)
  1376. self.ui.popmenu_save.setVisible(True)
  1377. edited_object = self.collection.get_active()
  1378. if isinstance(edited_object, FlatCAMGeometry):
  1379. # for now, if the Geometry is MultiGeo do not allow the editing
  1380. if edited_object.multigeo is True:
  1381. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1382. return
  1383. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1384. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1385. self.geo_editor.edit_fcgeometry(edited_object)
  1386. # we set the notebook to hidden
  1387. self.ui.splitter.setSizes([0, 1])
  1388. # set call source to the Editor we go into
  1389. self.call_source = 'geo_editor'
  1390. elif isinstance(edited_object, FlatCAMExcellon):
  1391. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1392. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1393. self.exc_editor.edit_fcexcellon(edited_object)
  1394. # set call source to the Editor we go into
  1395. self.call_source = 'exc_editor'
  1396. else:
  1397. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1398. return
  1399. # make sure that we can't select another object while in Editor Mode:
  1400. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1401. # delete any selection shape that might be active as they are not relevant in Editor
  1402. self.delete_selection_shape()
  1403. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1404. self.ui.plot_tab_area.protectTab(0)
  1405. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1406. self.should_we_save = True
  1407. def editor2object(self):
  1408. """
  1409. Transfers the Geometry or Excellon from the editor to the current object.
  1410. :return: None
  1411. """
  1412. self.report_usage("editor2object()")
  1413. # adjust the visibility of some of the canvas context menu
  1414. self.ui.popmenu_edit.setVisible(True)
  1415. self.ui.popmenu_save.setVisible(False)
  1416. edited_obj = self.collection.get_active()
  1417. obj_type = ""
  1418. if isinstance(edited_obj, FlatCAMGeometry):
  1419. obj_type = "Geometry"
  1420. self.geo_editor.update_fcgeometry(edited_obj)
  1421. self.geo_editor.update_options(edited_obj)
  1422. self.geo_editor.deactivate()
  1423. # update the geo object options so it is including the bounding box values
  1424. try:
  1425. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1426. edited_obj.options['xmin'] = xmin
  1427. edited_obj.options['ymin'] = ymin
  1428. edited_obj.options['xmax'] = xmax
  1429. edited_obj.options['ymax'] = ymax
  1430. except AttributeError:
  1431. self.inform.emit("[WARNING] Object empty after edit.")
  1432. elif isinstance(edited_obj, FlatCAMExcellon):
  1433. obj_type = "Excellon"
  1434. self.exc_editor.update_fcexcellon(edited_obj)
  1435. self.exc_editor.update_options(edited_obj)
  1436. self.exc_editor.deactivate()
  1437. else:
  1438. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1439. return
  1440. # if notebook is hidden we show it
  1441. if self.ui.splitter.sizes()[0] == 0:
  1442. self.ui.splitter.setSizes([1, 1])
  1443. # restore the call_source to app
  1444. self.call_source = 'app'
  1445. edited_obj.plot()
  1446. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1447. self.ui.plot_tab_area.protectTab(0)
  1448. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1449. # reset the Object UI to original settings
  1450. # edited_obj.set_ui(edited_obj.ui_type())
  1451. # edited_obj.build_ui()
  1452. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1453. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1454. def get_last_folder(self):
  1455. return self.defaults["global_last_folder"]
  1456. def get_last_save_folder(self):
  1457. loc = self.defaults["global_last_save_folder"]
  1458. if loc is None:
  1459. loc = self.defaults["global_last_folder"]
  1460. if loc is None:
  1461. loc = os.path.dirname(__file__)
  1462. return loc
  1463. def report_usage(self, resource):
  1464. """
  1465. Increments usage counter for the given resource
  1466. in self.defaults['global_stats'].
  1467. :param resource: Name of the resource.
  1468. :return: None
  1469. """
  1470. if resource in self.defaults['global_stats']:
  1471. self.defaults['global_stats'][resource] += 1
  1472. else:
  1473. self.defaults['global_stats'][resource] = 1
  1474. def init_tcl(self):
  1475. if hasattr(self,'tcl'):
  1476. # self.tcl = None
  1477. # TODO we need to clean non default variables and procedures here
  1478. # new object cannot be used here as it will not remember values created for next passes,
  1479. # because tcl was execudted in old instance of TCL
  1480. pass
  1481. else:
  1482. self.tcl = tk.Tcl()
  1483. self.setup_shell()
  1484. self.log.debug("TCL Shell has been initialized.")
  1485. # TODO: This shouldn't be here.
  1486. class TclErrorException(Exception):
  1487. """
  1488. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1489. """
  1490. pass
  1491. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1492. """
  1493. Shows a message on the FlatCAM Shell
  1494. :param msg: Message to display.
  1495. :param show: Opens the shell.
  1496. :param error: Shows the message as an error.
  1497. :return: None
  1498. """
  1499. if show:
  1500. self.ui.shell_dock.show()
  1501. try:
  1502. if error:
  1503. self.shell.append_error(msg + "\n")
  1504. elif warning:
  1505. self.shell.append_warning(msg + "\n")
  1506. elif success:
  1507. self.shell.append_success(msg + "\n")
  1508. elif selected:
  1509. self.shell.append_selected(msg + "\n")
  1510. else:
  1511. self.shell.append_output(msg + "\n")
  1512. except AttributeError:
  1513. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1514. def raise_tcl_unknown_error(self, unknownException):
  1515. """
  1516. Raise exception if is different type than TclErrorException
  1517. this is here mainly to show unknown errors inside TCL shell console.
  1518. :param unknownException:
  1519. :return:
  1520. """
  1521. if not isinstance(unknownException, self.TclErrorException):
  1522. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1523. else:
  1524. raise unknownException
  1525. def display_tcl_error(self, error, error_info=None):
  1526. """
  1527. escape bracket [ with \ otherwise there is error
  1528. "ERROR: missing close-bracket" instead of real error
  1529. :param error: it may be text or exception
  1530. :return: None
  1531. """
  1532. if isinstance(error, Exception):
  1533. exc_type, exc_value, exc_traceback = error_info
  1534. if not isinstance(error, self.TclErrorException):
  1535. show_trace = 1
  1536. else:
  1537. show_trace = int(self.defaults['global_verbose_error_level'])
  1538. if show_trace > 0:
  1539. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1540. trc_formated = []
  1541. for a in reversed(trc):
  1542. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1543. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1544. exc_type,
  1545. "\n".join(trc_formated))
  1546. else:
  1547. text = "%s" % error
  1548. else:
  1549. text = error
  1550. text = text.replace('[', '\\[').replace('"', '\\"')
  1551. self.tcl.eval('return -code error "%s"' % text)
  1552. def raise_tcl_error(self, text):
  1553. """
  1554. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1555. :param text: text of error
  1556. :return: raise exception
  1557. """
  1558. self.display_tcl_error(text)
  1559. raise self.TclErrorException(text)
  1560. def exec_command(self, text):
  1561. """
  1562. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1563. Also handles execution in separated threads
  1564. :param text:
  1565. :return: output if there was any
  1566. """
  1567. self.report_usage('exec_command')
  1568. result = self.exec_command_test(text, False)
  1569. #MS: added this method call so the geometry is updated once the TCL
  1570. #command is executed
  1571. self.plot_all()
  1572. return result
  1573. def exec_command_test(self, text, reraise=True):
  1574. """
  1575. Same as exec_command(...) with additional control over exceptions.
  1576. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1577. :param text: Input command
  1578. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1579. :return: Output from the command
  1580. """
  1581. text = str(text)
  1582. try:
  1583. self.shell.open_proccessing() # Disables input box.
  1584. result = self.tcl.eval(str(text))
  1585. if result != 'None':
  1586. self.shell.append_output(result + '\n')
  1587. except tk.TclError as e:
  1588. # This will display more precise answer if something in TCL shell fails
  1589. result = self.tcl.eval("set errorInfo")
  1590. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1591. self.shell.append_error('ERROR: ' + result + '\n')
  1592. # Show error in console and just return or in test raise exception
  1593. if reraise:
  1594. raise e
  1595. finally:
  1596. self.shell.close_proccessing()
  1597. pass
  1598. return result
  1599. # """
  1600. # Code below is unsused. Saved for later.
  1601. # """
  1602. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1603. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1604. # self.log.debug(parts)
  1605. # try:
  1606. # if parts[0] not in commands:
  1607. # self.shell.append_error("Unknown command\n")
  1608. # return
  1609. #
  1610. # #import inspect
  1611. # #inspect.getargspec(someMethod)
  1612. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1613. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1614. # self.shell.append_error(
  1615. # "Command %s takes %d arguments. %d given.\n" %
  1616. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1617. # )
  1618. # return
  1619. #
  1620. # cmdfcn = commands[parts[0]]["fcn"]
  1621. # cmdconv = commands[parts[0]]["converters"]
  1622. # if len(parts) - 1 > 0:
  1623. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1624. # else:
  1625. # retval = cmdfcn()
  1626. # retfcn = commands[parts[0]]["retfcn"]
  1627. # if retval and retfcn(retval):
  1628. # self.shell.append_output(retfcn(retval) + "\n")
  1629. #
  1630. # except Exception as e:
  1631. # #self.shell.append_error(''.join(traceback.format_exc()))
  1632. # #self.shell.append_error("?\n")
  1633. # self.shell.append_error(str(e) + "\n")
  1634. def info(self, msg):
  1635. """
  1636. Informs the user. Normally on the status bar, optionally
  1637. also on the shell.
  1638. :param msg: Text to write.
  1639. :return: None
  1640. """
  1641. # Type of message in brackets at the begining of the message.
  1642. match = re.search("\[([^\]]+)\](.*)", msg)
  1643. if match:
  1644. level = match.group(1)
  1645. msg_ = match.group(2)
  1646. self.ui.fcinfo.set_status(str(msg_), level=level)
  1647. if level.lower() == "error":
  1648. self.shell_message(msg, error=True, show=True)
  1649. elif level.lower() == "warning":
  1650. self.shell_message(msg, warning=True, show=True)
  1651. elif level.lower() == "error_notcl":
  1652. self.shell_message(msg, error=True, show=False)
  1653. elif level.lower() == "warning_notcl":
  1654. self.shell_message(msg, warning=True, show=False)
  1655. elif level.lower() == "success":
  1656. self.shell_message(msg, success=True, show=False)
  1657. elif level.lower() == "selected":
  1658. self.shell_message(msg, selected=True, show=False)
  1659. else:
  1660. self.shell_message(msg, show=False)
  1661. else:
  1662. self.ui.fcinfo.set_status(str(msg), level="info")
  1663. # make sure that if the message is to clear the infobar with a space
  1664. # is not printed over and over on the shell
  1665. if msg != '':
  1666. self.shell_message(msg)
  1667. def restore_toolbar_view(self):
  1668. tb = self.defaults["global_toolbar_view"]
  1669. if tb & 1:
  1670. self.ui.toolbarfile.setVisible(True)
  1671. else:
  1672. self.ui.toolbarfile.setVisible(False)
  1673. if tb & 2:
  1674. self.ui.toolbargeo.setVisible(True)
  1675. else:
  1676. self.ui.toolbargeo.setVisible(False)
  1677. if tb & 4:
  1678. self.ui.toolbarview.setVisible(True)
  1679. else:
  1680. self.ui.toolbarview.setVisible(False)
  1681. if tb & 8:
  1682. self.ui.toolbartools.setVisible(True)
  1683. else:
  1684. self.ui.toolbartools.setVisible(False)
  1685. if tb & 16:
  1686. self.ui.exc_edit_toolbar.setVisible(True)
  1687. else:
  1688. self.ui.exc_edit_toolbar.setVisible(False)
  1689. if tb & 32:
  1690. self.ui.geo_edit_toolbar.setVisible(True)
  1691. else:
  1692. self.ui.geo_edit_toolbar.setVisible(False)
  1693. if tb & 64:
  1694. self.ui.snap_toolbar.setVisible(True)
  1695. else:
  1696. self.ui.snap_toolbar.setVisible(False)
  1697. def load_defaults(self, filename):
  1698. """
  1699. Loads the aplication's default settings from current_defaults.FlatConfig into
  1700. ``self.defaults``.
  1701. :return: None
  1702. """
  1703. try:
  1704. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1705. options = f.read()
  1706. f.close()
  1707. except IOError:
  1708. self.log.error("Could not load defaults file.")
  1709. self.inform.emit("[ERROR] Could not load defaults file.")
  1710. # in case the defaults file can't be loaded, show all toolbars
  1711. self.defaults["global_toolbar_view"] = 127
  1712. return
  1713. try:
  1714. defaults = json.loads(options)
  1715. except:
  1716. # in case the defaults file can't be loaded, show all toolbars
  1717. self.defaults["global_toolbar_view"] = 127
  1718. e = sys.exc_info()[0]
  1719. App.log.error(str(e))
  1720. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1721. return
  1722. self.defaults.update(defaults)
  1723. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1724. # restore the toolbar view
  1725. self.restore_toolbar_view()
  1726. def on_import_preferences(self):
  1727. """
  1728. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1729. ``self.defaults``.
  1730. :return: None
  1731. """
  1732. self.report_usage("on_import_preferences")
  1733. App.log.debug("on_import_preferences()")
  1734. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1735. try:
  1736. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1737. directory=self.data_path, filter=filter)
  1738. except TypeError:
  1739. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1740. filename = str(filename)
  1741. if filename == "":
  1742. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1743. else:
  1744. try:
  1745. f = open(filename)
  1746. options = f.read()
  1747. f.close()
  1748. except IOError:
  1749. self.log.error("Could not load defaults file.")
  1750. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1751. return
  1752. try:
  1753. defaults_from_file = json.loads(options)
  1754. except:
  1755. e = sys.exc_info()[0]
  1756. App.log.error(str(e))
  1757. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1758. return
  1759. self.defaults.update(defaults_from_file)
  1760. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1761. def on_export_preferences(self):
  1762. self.report_usage("on_export_preferences")
  1763. App.log.debug("on_export_preferences()")
  1764. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1765. try:
  1766. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1767. caption="Export FlatCAM Preferences",
  1768. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1769. )
  1770. except TypeError:
  1771. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1772. filename = str(filename)
  1773. defaults_from_file = {}
  1774. if filename == "":
  1775. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1776. return
  1777. else:
  1778. try:
  1779. f = open(filename, 'w')
  1780. defaults_file_content = f.read()
  1781. f.close()
  1782. except IOError:
  1783. App.log.debug('Creating a new preferences file ...')
  1784. f = open(filename, 'w')
  1785. json.dump({}, f)
  1786. f.close()
  1787. except:
  1788. e = sys.exc_info()[0]
  1789. App.log.error("Could not load defaults file.")
  1790. App.log.error(str(e))
  1791. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1792. return
  1793. try:
  1794. defaults_from_file = json.loads(defaults_file_content)
  1795. except:
  1796. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1797. # Update options
  1798. self.defaults_read_form()
  1799. defaults_from_file.update(self.defaults)
  1800. self.propagate_defaults(silent=True)
  1801. # Save update options
  1802. try:
  1803. f = open(filename, "w")
  1804. json.dump(defaults_from_file, f)
  1805. f.close()
  1806. except:
  1807. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1808. return
  1809. self.file_saved.emit("preferences", filename)
  1810. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1811. def on_preferences_open_folder(self):
  1812. self.report_usage("on_preferences_open_folder()")
  1813. if sys.platform == 'win32':
  1814. subprocess.Popen('explorer %s' % self.data_path)
  1815. elif sys.platform == 'darwin':
  1816. os.system('open "%s"' % self.data_path)
  1817. else:
  1818. subprocess.Popen(['xdg-open', self.data_path])
  1819. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1820. def save_geometry(self, x, y, width, height, notebook_width):
  1821. self.defaults["global_def_win_x"] = x
  1822. self.defaults["global_def_win_y"] = y
  1823. self.defaults["global_def_win_w"] = width
  1824. self.defaults["global_def_win_h"] = height
  1825. self.defaults["def_notebook_width"] = notebook_width
  1826. self.save_defaults()
  1827. def message_dialog(self, title, message, kind="info"):
  1828. icon = {"info": QtWidgets.QMessageBox.Information,
  1829. "warning": QtWidgets.QMessageBox.Warning,
  1830. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1831. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1832. dlg.setText(message)
  1833. dlg.exec_()
  1834. def register_recent(self, kind, filename):
  1835. self.log.debug("register_recent()")
  1836. self.log.debug(" %s" % kind)
  1837. self.log.debug(" %s" % filename)
  1838. record = {'kind': str(kind), 'filename': str(filename)}
  1839. if record in self.recent:
  1840. return
  1841. self.recent.insert(0, record)
  1842. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1843. self.recent.pop()
  1844. try:
  1845. f = open(self.data_path + '/recent.json', 'w')
  1846. except IOError:
  1847. App.log.error("Failed to open recent items file for writing.")
  1848. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1849. return
  1850. #try:
  1851. json.dump(self.recent, f)
  1852. # except:
  1853. # App.log.error("Failed to write to recent items file.")
  1854. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1855. # f.close()
  1856. f.close()
  1857. # Re-buid the recent items menu
  1858. self.setup_recent_items()
  1859. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1860. """
  1861. Creates a new specalized FlatCAMObj and attaches it to the application,
  1862. this is, updates the GUI accordingly, any other records and plots it.
  1863. This method is thread-safe.
  1864. Notes:
  1865. * If the name is in use, the self.collection will modify it
  1866. when appending it to the collection. There is no need to handle
  1867. name conflicts here.
  1868. :param kind: The kind of object to create. One of 'gerber',
  1869. 'excellon', 'cncjob' and 'geometry'.
  1870. :type kind: str
  1871. :param name: Name for the object.
  1872. :type name: str
  1873. :param initialize: Function to run after creation of the object
  1874. but before it is attached to the application. The function is
  1875. called with 2 parameters: the new object and the App instance.
  1876. :type initialize: function
  1877. :return: None
  1878. :rtype: None
  1879. """
  1880. App.log.debug("new_object()")
  1881. self.plot = plot
  1882. self.autoselected = autoselected
  1883. t0 = time.time() # Debug
  1884. ## Create object
  1885. classdict = {
  1886. "gerber": FlatCAMGerber,
  1887. "excellon": FlatCAMExcellon,
  1888. "cncjob": FlatCAMCNCjob,
  1889. "geometry": FlatCAMGeometry
  1890. }
  1891. App.log.debug("Calling object constructor...")
  1892. obj = classdict[kind](name)
  1893. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1894. # Set options from "Project options" form
  1895. self.options_read_form()
  1896. # IMPORTANT
  1897. # The key names in defaults and options dictionary's are not random:
  1898. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1899. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1900. # the options from project options form into the self.options. After that, below, depending on the type of
  1901. # object that is created, it will strip the name of the object and the underline (if the original key was
  1902. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1903. # "toolchange"
  1904. for option in self.options:
  1905. if option.find(kind + "_") == 0:
  1906. oname = option[len(kind) + 1:]
  1907. obj.options[oname] = self.options[option]
  1908. # if kind == 'geometry':
  1909. # obj.tools = {}
  1910. # elif kind == 'cncjob':
  1911. # obj.cnc_tools = {}
  1912. # Initialize as per user request
  1913. # User must take care to implement initialize
  1914. # in a thread-safe way as is is likely that we
  1915. # have been invoked in a separate thread.
  1916. t1 = time.time()
  1917. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1918. try:
  1919. return_value = initialize(obj, self)
  1920. except Exception as e:
  1921. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1922. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1923. msg += traceback.format_exc()
  1924. self.inform.emit(msg)
  1925. # if str(e) == "Empty Geometry":
  1926. # self.inform.emit("[ERROR_NOTCL] )
  1927. # else:
  1928. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1929. return "fail"
  1930. t2 = time.time()
  1931. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1932. if return_value == 'fail':
  1933. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1934. return "fail"
  1935. # Check units and convert if necessary
  1936. # This condition CAN be true because initialize() can change obj.units
  1937. if self.options["units"].upper() != obj.units.upper():
  1938. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1939. obj.convert_units(self.options["units"])
  1940. t3 = time.time()
  1941. self.log.debug("%f seconds converting units." % (t3 - t2))
  1942. # Create the bounding box for the object and then add the results to the obj.options
  1943. try:
  1944. xmin, ymin, xmax, ymax = obj.bounds()
  1945. obj.options['xmin'] = xmin
  1946. obj.options['ymin'] = ymin
  1947. obj.options['xmax'] = xmax
  1948. obj.options['ymax'] = ymax
  1949. except:
  1950. log.warning("The object has no bounds properties.")
  1951. # don't plot objects with no bounds, there is nothing to plot
  1952. self.plot = False
  1953. pass
  1954. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1955. # Move the object to the main thread and let the app know that it is available.
  1956. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1957. self.object_created.emit(obj, self.plot, self.autoselected)
  1958. return obj
  1959. def new_excellon_object(self):
  1960. self.report_usage("new_excellon_object()")
  1961. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  1962. def new_geometry_object(self):
  1963. self.report_usage("new_geometry_object()")
  1964. def initialize(obj, self):
  1965. obj.multitool = False
  1966. self.new_object('geometry', 'new_g', initialize, plot=False)
  1967. def on_object_created(self, obj, plot, autoselect):
  1968. """
  1969. Event callback for object creation.
  1970. :param obj: The newly created FlatCAM object.
  1971. :return: None
  1972. """
  1973. t0 = time.time() # DEBUG
  1974. self.log.debug("on_object_created()")
  1975. # The Collection might change the name if there is a collision
  1976. self.collection.append(obj)
  1977. # after adding the object to the collection always update the list of objects that are in the collection
  1978. self.all_objects_list = self.collection.get_list()
  1979. # self.inform.emit('[selected] %s created & selected: %s' %
  1980. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  1981. if obj.kind == 'gerber':
  1982. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1983. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  1984. elif obj.kind == 'excellon':
  1985. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1986. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  1987. elif obj.kind == 'cncjob':
  1988. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1989. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  1990. elif obj.kind == 'geometry':
  1991. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1992. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  1993. # self.new_object_available.emit(obj)
  1994. # update the SHELL auto-completer model with the name of the new object
  1995. self.myKeywords.append(obj.options['name'])
  1996. self.shell._edit.set_model_data(self.myKeywords)
  1997. if autoselect:
  1998. # select the just opened object but deselect the previous ones
  1999. self.collection.set_all_inactive()
  2000. self.collection.set_active(obj.options["name"])
  2001. # here it is done the object plotting
  2002. def worker_task(obj):
  2003. with self.proc_container.new("Plotting"):
  2004. if isinstance(obj, FlatCAMCNCjob):
  2005. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2006. else:
  2007. obj.plot()
  2008. t1 = time.time() # DEBUG
  2009. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2010. self.object_plotted.emit(obj)
  2011. # Send to worker
  2012. # self.worker.add_task(worker_task, [self])
  2013. if plot is True:
  2014. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2015. def on_object_changed(self, obj):
  2016. # update the bounding box data from obj.options
  2017. xmin, ymin, xmax, ymax = obj.bounds()
  2018. obj.options['xmin'] = xmin
  2019. obj.options['ymin'] = ymin
  2020. obj.options['xmax'] = xmax
  2021. obj.options['ymax'] = ymax
  2022. log.debug("Object changed, updating the bounding box data on self.options")
  2023. # delete the old selection shape
  2024. self.delete_selection_shape()
  2025. self.should_we_save = True
  2026. def on_object_plotted(self, obj):
  2027. self.on_zoom_fit(None)
  2028. def options_read_form(self):
  2029. for option in self.options_form_fields:
  2030. self.options[option] = self.options_form_fields[option].get_value()
  2031. def options_write_form(self):
  2032. for option in self.options:
  2033. self.options_write_form_field(option)
  2034. def options_write_form_field(self, field):
  2035. try:
  2036. self.options_form_fields[field].set_value(self.options[field])
  2037. except KeyError:
  2038. # Changed from error to debug. This allows to have data stored
  2039. # which is not user-editable.
  2040. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2041. pass
  2042. def on_about(self):
  2043. """
  2044. Displays the "about" dialog.
  2045. :return: None
  2046. """
  2047. self.report_usage("on_about")
  2048. version = self.version
  2049. version_date = self.version_date
  2050. beta = self.beta
  2051. class AboutDialog(QtWidgets.QDialog):
  2052. def __init__(self, parent=None):
  2053. QtWidgets.QDialog.__init__(self, parent)
  2054. # Icon and title
  2055. self.setWindowIcon(parent.app_icon)
  2056. self.setWindowTitle("FlatCAM")
  2057. layout1 = QtWidgets.QVBoxLayout()
  2058. self.setLayout(layout1)
  2059. layout2 = QtWidgets.QHBoxLayout()
  2060. layout1.addLayout(layout2)
  2061. logo = QtWidgets.QLabel()
  2062. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2063. layout2.addWidget(logo, stretch=0)
  2064. title = QtWidgets.QLabel(
  2065. "<font size=8><B>FlatCAM</B></font><BR>"
  2066. "Version %s %s (%s) - %s <BR>"
  2067. "<BR>"
  2068. "2D Computer-Aided Printed Circuit Board<BR>"
  2069. "Manufacturing.<BR>"
  2070. "<BR>"
  2071. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2072. "<BR>"
  2073. "<B> Main Contributors:</B><BR>"
  2074. "Denis Hayrullin<BR>"
  2075. "Kamil Sopko<BR>"
  2076. "Marius Stanciu<BR>"
  2077. "Matthieu Berthomé<BR>"
  2078. "and many others found "
  2079. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2080. "<BR>"
  2081. "Development is done "
  2082. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2083. "DOWNLOAD area "
  2084. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2085. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2086. )
  2087. title.setOpenExternalLinks(True)
  2088. layout2.addWidget(title, stretch=1)
  2089. layout3 = QtWidgets.QHBoxLayout()
  2090. layout1.addLayout(layout3)
  2091. layout3.addStretch()
  2092. okbtn = QtWidgets.QPushButton("Close")
  2093. layout3.addWidget(okbtn)
  2094. okbtn.clicked.connect(self.accept)
  2095. AboutDialog(self.ui).exec_()
  2096. def on_file_savedefaults(self):
  2097. """
  2098. Callback for menu item File->Save Defaults. Saves application default options
  2099. ``self.defaults`` to current_defaults.FlatConfig.
  2100. :return: None
  2101. """
  2102. self.save_defaults()
  2103. def on_app_exit(self):
  2104. self.report_usage("on_app_exit()")
  2105. if self.collection.get_list():
  2106. msgbox = QtWidgets.QMessageBox()
  2107. # msgbox.setText("<B>Save changes ...</B>")
  2108. msgbox.setText("There are files/objects opened in FlatCAM. "
  2109. "\n"
  2110. "Do you want to Save the project?")
  2111. msgbox.setWindowTitle("Save changes")
  2112. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2113. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2114. QtWidgets.QMessageBox.Cancel)
  2115. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2116. response = msgbox.exec_()
  2117. if response == QtWidgets.QMessageBox.Yes:
  2118. self.on_file_saveprojectas(thread=False)
  2119. elif response == QtWidgets.QMessageBox.Cancel:
  2120. return
  2121. self.save_defaults()
  2122. else:
  2123. self.save_defaults()
  2124. log.debug("Application defaults saved ... Exit event.")
  2125. QtWidgets.qApp.quit()
  2126. def save_defaults(self, silent=False):
  2127. """
  2128. Saves application default options
  2129. ``self.defaults`` to current_defaults.FlatConfig.
  2130. :return: None
  2131. """
  2132. self.report_usage("save_defaults")
  2133. # Read options from file
  2134. try:
  2135. f = open(self.data_path + "/current_defaults.FlatConfig")
  2136. defaults_file_content = f.read()
  2137. f.close()
  2138. except:
  2139. e = sys.exc_info()[0]
  2140. App.log.error("Could not load defaults file.")
  2141. App.log.error(str(e))
  2142. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2143. return
  2144. try:
  2145. defaults = json.loads(defaults_file_content)
  2146. except:
  2147. e = sys.exc_info()[0]
  2148. App.log.error("Failed to parse defaults file.")
  2149. App.log.error(str(e))
  2150. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2151. return
  2152. # Update options
  2153. self.defaults_read_form()
  2154. defaults.update(self.defaults)
  2155. self.propagate_defaults(silent=True)
  2156. # Save update options
  2157. try:
  2158. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2159. json.dump(defaults, f)
  2160. f.close()
  2161. except:
  2162. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2163. return
  2164. # Save the toolbar view
  2165. tb_status = 0
  2166. if self.ui.toolbarfile.isVisible():
  2167. tb_status += 1
  2168. if self.ui.toolbargeo.isVisible():
  2169. tb_status += 2
  2170. if self.ui.toolbarview.isVisible():
  2171. tb_status += 4
  2172. if self.ui.toolbartools.isVisible():
  2173. tb_status += 8
  2174. if self.ui.exc_edit_toolbar.isVisible():
  2175. tb_status += 16
  2176. if self.ui.geo_edit_toolbar.isVisible():
  2177. tb_status += 32
  2178. if self.ui.snap_toolbar.isVisible():
  2179. tb_status += 64
  2180. self.defaults["global_toolbar_view"] = tb_status
  2181. if not silent:
  2182. self.inform.emit("[success]Defaults saved.")
  2183. def save_factory_defaults(self, silent=False):
  2184. """
  2185. Saves application factory default options
  2186. ``self.defaults`` to factory_defaults.FlatConfig.
  2187. It's a one time job done just after the first install.
  2188. :return: None
  2189. """
  2190. self.report_usage("save_factory_defaults")
  2191. # Read options from file
  2192. try:
  2193. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2194. factory_defaults_file_content = f_f_def.read()
  2195. f_f_def.close()
  2196. except:
  2197. e = sys.exc_info()[0]
  2198. App.log.error("Could not load factory defaults file.")
  2199. App.log.error(str(e))
  2200. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2201. return
  2202. try:
  2203. factory_defaults = json.loads(factory_defaults_file_content)
  2204. except:
  2205. e = sys.exc_info()[0]
  2206. App.log.error("Failed to parse factory defaults file.")
  2207. App.log.error(str(e))
  2208. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2209. return
  2210. # Update options
  2211. self.defaults_read_form()
  2212. factory_defaults.update(self.defaults)
  2213. self.propagate_defaults(silent=True)
  2214. # Save update options
  2215. try:
  2216. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2217. json.dump(factory_defaults, f_f_def_s)
  2218. f_f_def_s.close()
  2219. except:
  2220. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2221. return
  2222. if silent is False:
  2223. self.inform.emit("Factory defaults saved.")
  2224. def final_save(self):
  2225. if self.should_we_save and self.collection.get_list():
  2226. msgbox = QtWidgets.QMessageBox()
  2227. # msgbox.setText("<B>Save changes ...</B>")
  2228. msgbox.setText("There are files/objects modified in FlatCAM. "
  2229. "\n"
  2230. "Do you want to Save the project?")
  2231. msgbox.setWindowTitle("Save changes")
  2232. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2233. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2234. QtWidgets.QMessageBox.Cancel)
  2235. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2236. response = msgbox.exec_()
  2237. if response == QtWidgets.QMessageBox.Yes:
  2238. self.on_file_saveprojectas(thread=False)
  2239. elif response == QtWidgets.QMessageBox.Cancel:
  2240. self.should_we_quit = False
  2241. return
  2242. self.save_defaults()
  2243. log.debug("Application defaults saved ... Exit event.")
  2244. def on_toggle_shell(self):
  2245. """
  2246. toggle shell if is visible close it if closed open it
  2247. :return:
  2248. """
  2249. self.report_usage("on_toggle_shell()")
  2250. if self.ui.shell_dock.isVisible():
  2251. self.ui.shell_dock.hide()
  2252. else:
  2253. self.ui.shell_dock.show()
  2254. def on_edit_join(self, name=None):
  2255. """
  2256. Callback for Edit->Join. Joins the selected geometry objects into
  2257. a new one.
  2258. :return: None
  2259. """
  2260. self.report_usage("on_edit_join()")
  2261. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2262. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2263. tooldias = []
  2264. geo_type_list = []
  2265. objs = self.collection.get_selected()
  2266. for obj in objs:
  2267. geo_type_list.append(obj.multigeo)
  2268. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2269. if len(set(geo_type_list)) != 1:
  2270. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2271. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2272. "convert from one to another and retry joining \n"
  2273. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2274. "the result may not be what was expected. \n"
  2275. "Check the generated GCODE.")
  2276. return
  2277. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2278. if True in geo_type_list:
  2279. def initialize(obj, app):
  2280. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2281. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2282. for v in obj.tools.values():
  2283. v['data']['name'] = obj_name_multi
  2284. self.new_object("geometry", obj_name_multi, initialize)
  2285. else:
  2286. def initialize(obj, app):
  2287. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2288. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2289. for v in obj.tools.values():
  2290. v['data']['name'] = obj_name_single
  2291. self.new_object("geometry", obj_name_single, initialize)
  2292. self.should_we_save = True
  2293. def on_edit_join_exc(self):
  2294. """
  2295. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2296. a new one.
  2297. :return: None
  2298. """
  2299. self.report_usage("on_edit_join_exc()")
  2300. objs = self.collection.get_selected()
  2301. for obj in objs:
  2302. if not isinstance(obj, FlatCAMExcellon):
  2303. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2304. return
  2305. def initialize(obj, app):
  2306. FlatCAMExcellon.merge(objs, obj)
  2307. self.new_object("excellon", 'Combo_Excellon', initialize)
  2308. self.should_we_save = True
  2309. def on_edit_join_grb(self):
  2310. """
  2311. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2312. a new one.
  2313. :return: None
  2314. """
  2315. self.report_usage("on_edit_join_grb()")
  2316. objs = self.collection.get_selected()
  2317. for obj in objs:
  2318. if not isinstance(obj, FlatCAMGerber):
  2319. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2320. return
  2321. def initialize(obj, app):
  2322. FlatCAMGerber.merge(objs, obj)
  2323. self.new_object("gerber", 'Combo_Gerber', initialize)
  2324. self.should_we_save = True
  2325. def on_convert_singlegeo_to_multigeo(self):
  2326. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2327. obj = self.collection.get_active()
  2328. if obj is None:
  2329. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2330. return
  2331. if not isinstance(obj, FlatCAMGeometry):
  2332. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2333. return
  2334. obj.multigeo = True
  2335. for tooluid, dict_value in obj.tools.items():
  2336. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2337. if not isinstance(obj.solid_geometry, list):
  2338. obj.solid_geometry = [obj.solid_geometry]
  2339. obj.solid_geometry[:] = []
  2340. obj.plot()
  2341. self.should_we_save = True
  2342. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2343. def on_convert_multigeo_to_singlegeo(self):
  2344. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2345. obj = self.collection.get_active()
  2346. if obj is None:
  2347. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2348. return
  2349. if not isinstance(obj, FlatCAMGeometry):
  2350. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2351. return
  2352. obj.multigeo = False
  2353. total_solid_geometry = []
  2354. for tooluid, dict_value in obj.tools.items():
  2355. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2356. # clear the original geometry
  2357. dict_value['solid_geometry'][:] = []
  2358. obj.solid_geometry = deepcopy(total_solid_geometry)
  2359. obj.plot()
  2360. self.should_we_save = True
  2361. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2362. def on_options_dict_change(self, field):
  2363. self.options_write_form_field(field)
  2364. if field == "units":
  2365. self.set_screen_units(self.options['units'])
  2366. def on_defaults_dict_change(self, field):
  2367. self.defaults_write_form_field(field)
  2368. def set_screen_units(self, units):
  2369. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2370. def on_toggle_units(self):
  2371. """
  2372. Callback for the Units radio-button change in the Options tab.
  2373. Changes the application's default units or the current project's units.
  2374. If changing the project's units, the change propagates to all of
  2375. the objects in the project.
  2376. :return: None
  2377. """
  2378. self.report_usage("on_toggle_units")
  2379. if self.toggle_units_ignore:
  2380. return
  2381. # If option is the same, then ignore
  2382. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2383. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2384. return
  2385. # Options to scale
  2386. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2387. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2388. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2389. 'gerber_noncoppermargin','gerber_bboxmargin',
  2390. 'excellon_drillz', "excellon_toolchangexy",
  2391. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2392. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2393. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2394. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2395. 'geometry_toolchangez',
  2396. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2397. def scale_options(sfactor):
  2398. for dim in dimensions:
  2399. if dim == 'excellon_toolchangexy':
  2400. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2401. coords_xy[0] *= sfactor
  2402. coords_xy[1] *= sfactor
  2403. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2404. elif dim == 'geometry_toolchangexy':
  2405. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2406. coords_xy[0] *= sfactor
  2407. coords_xy[1] *= sfactor
  2408. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2409. else:
  2410. self.options[dim] *= sfactor
  2411. # The scaling factor depending on choice of units.
  2412. factor = 1/25.4
  2413. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2414. factor = 25.4
  2415. # Changing project units. Warn user.
  2416. msgbox = QtWidgets.QMessageBox()
  2417. msgbox.setText("<B>Change project units ...</B>")
  2418. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2419. "properties of all objects to be scaled accordingly. Continue?")
  2420. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2421. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2422. response = msgbox.exec_()
  2423. if response == QtWidgets.QMessageBox.Ok:
  2424. self.options_read_form()
  2425. scale_options(factor)
  2426. self.options_write_form()
  2427. self.should_we_save = True
  2428. # change this only if the workspace is active
  2429. if self.defaults['global_workspace'] is True:
  2430. self.plotcanvas.draw_workspace()
  2431. # adjust the grid values on the main toolbar
  2432. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2433. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2434. for obj in self.collection.get_list():
  2435. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2436. obj.convert_units(units)
  2437. # make that the properties stored in the object are also updated
  2438. self.object_changed.emit(obj)
  2439. obj.build_ui()
  2440. current = self.collection.get_active()
  2441. if current is not None:
  2442. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2443. if not isinstance(current, FlatCAMGeometry):
  2444. current.to_form()
  2445. self.plot_all()
  2446. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2447. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2448. self.set_screen_units(self.options["units"])
  2449. else:
  2450. # Undo toggling
  2451. self.toggle_units_ignore = True
  2452. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2453. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2454. else:
  2455. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2456. self.toggle_units_ignore = False
  2457. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2458. self.options_read_form()
  2459. def on_toggle_units_click(self):
  2460. if self.options["units"] == 'MM':
  2461. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2462. else:
  2463. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2464. self.on_toggle_units()
  2465. def on_language_apply(self):
  2466. self.report_usage("on_language_apply()")
  2467. # TODO: apply the language
  2468. # app restart section
  2469. pass
  2470. def on_fullscreen(self):
  2471. self.report_usage("on_fullscreen()")
  2472. if self.toggle_fscreen is False:
  2473. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2474. tb.setVisible(False)
  2475. self.ui.splitter_left.setVisible(False)
  2476. self.toggle_fscreen = True
  2477. else:
  2478. self.restore_toolbar_view()
  2479. self.ui.splitter_left.setVisible(True)
  2480. self.toggle_fscreen = False
  2481. def on_toggle_plotarea(self):
  2482. self.report_usage("on_toggle_plotarea()")
  2483. try:
  2484. name = self.ui.plot_tab_area.widget(0).objectName()
  2485. except AttributeError:
  2486. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2487. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2488. self.ui.plot_tab_area.protectTab(0)
  2489. return
  2490. if name != 'plotarea':
  2491. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2492. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2493. self.ui.plot_tab_area.protectTab(0)
  2494. else:
  2495. self.ui.plot_tab_area.closeTab(0)
  2496. def on_toggle_notebook(self):
  2497. if self.ui.splitter.sizes()[0] == 0:
  2498. self.ui.splitter.setSizes([1, 1])
  2499. else:
  2500. self.ui.splitter.setSizes([0, 1])
  2501. def on_toggle_axis(self):
  2502. self.report_usage("on_toggle_axis()")
  2503. if self.toggle_axis is False:
  2504. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2505. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2506. self.plotcanvas.redraw()
  2507. self.toggle_axis = True
  2508. else:
  2509. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2510. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2511. self.plotcanvas.redraw()
  2512. self.toggle_axis = False
  2513. def on_toggle_grid(self):
  2514. self.report_usage("on_toggle_grid()")
  2515. self.ui.grid_snap_btn.trigger()
  2516. def on_options_combo_change(self, sel):
  2517. """
  2518. Called when the combo box to choose between application defaults and
  2519. project option changes value. The corresponding variables are
  2520. copied to the UI.
  2521. :param sel: The option index that was chosen.
  2522. :return: None
  2523. """
  2524. # combo_sel = self.ui.notebook.combo_options.get_active()
  2525. App.log.debug("Options --> %s" % sel)
  2526. # form = [self.defaults_form, self.options_form][sel]
  2527. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2528. if sel == 0:
  2529. self.gen_form = self.general_defaults_form
  2530. self.ger_form = self.gerber_defaults_form
  2531. self.exc_form = self.excellon_defaults_form
  2532. self.geo_form = self.geometry_defaults_form
  2533. self.cnc_form = self.cncjob_defaults_form
  2534. self.tools_form = self.tools_defaults_form
  2535. elif sel == 1:
  2536. self.gen_form = self.general_options_form
  2537. self.ger_form = self.gerber_options_form
  2538. self.exc_form = self.excellon_options_form
  2539. self.geo_form = self.geometry_options_form
  2540. self.cnc_form = self.cncjob_options_form
  2541. self.tools_form = self.tools_options_form
  2542. else:
  2543. return
  2544. try:
  2545. self.ui.general_scroll_area.takeWidget()
  2546. except:
  2547. self.log.debug("Nothing to remove")
  2548. self.ui.general_scroll_area.setWidget(self.gen_form)
  2549. self.gen_form.show()
  2550. try:
  2551. self.ui.gerber_scroll_area.takeWidget()
  2552. except:
  2553. self.log.debug("Nothing to remove")
  2554. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2555. self.ger_form.show()
  2556. try:
  2557. self.ui.excellon_scroll_area.takeWidget()
  2558. except:
  2559. self.log.debug("Nothing to remove")
  2560. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2561. self.exc_form.show()
  2562. try:
  2563. self.ui.geometry_scroll_area.takeWidget()
  2564. except:
  2565. self.log.debug("Nothing to remove")
  2566. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2567. self.geo_form.show()
  2568. try:
  2569. self.ui.cncjob_scroll_area.takeWidget()
  2570. except:
  2571. self.log.debug("Nothing to remove")
  2572. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2573. self.cnc_form.show()
  2574. try:
  2575. self.ui.tools_scroll_area.takeWidget()
  2576. except:
  2577. self.log.debug("Nothing to remove")
  2578. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2579. self.tools_form.show()
  2580. self.log.debug("Finished GUI form initialization.")
  2581. # self.options2form()
  2582. def on_excellon_defaults_button(self):
  2583. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2584. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2585. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2586. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2587. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2588. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2589. log.debug("Excellon app defaults loaded ...")
  2590. def on_excellon_options_button(self):
  2591. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2592. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2593. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2594. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2595. self.options_form_fields["excellon_zeros"].set_value('L')
  2596. self.options_form_fields["excellon_units"].set_value('INCH')
  2597. log.debug("Excellon options defaults loaded ...")
  2598. # Setting plot colors handlers
  2599. def on_pf_color_entry(self):
  2600. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2601. self.defaults['global_plot_fill'][7:9]
  2602. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2603. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2604. def on_pf_color_button(self):
  2605. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2606. c_dialog = QtWidgets.QColorDialog()
  2607. plot_fill_color = c_dialog.getColor(initial=current_color)
  2608. if plot_fill_color.isValid() is False:
  2609. return
  2610. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2611. "background-color:%s" % str(plot_fill_color.name()))
  2612. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2613. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2614. self.defaults['global_plot_fill'] = new_val
  2615. def on_pf_color_spinner(self):
  2616. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2617. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2618. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2619. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2620. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2621. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2622. def on_pf_color_slider(self):
  2623. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2624. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2625. def on_pl_color_entry(self):
  2626. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2627. self.defaults['global_plot_line'][7:9]
  2628. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2629. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2630. def on_pl_color_button(self):
  2631. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2632. # print(current_color)
  2633. c_dialog = QtWidgets.QColorDialog()
  2634. plot_line_color = c_dialog.getColor(initial=current_color)
  2635. if plot_line_color.isValid() is False:
  2636. return
  2637. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2638. "background-color:%s" % str(plot_line_color.name()))
  2639. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2640. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2641. self.defaults['global_plot_line'] = new_val_line
  2642. # Setting selection colors (left - right) handlers
  2643. def on_sf_color_entry(self):
  2644. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2645. self.defaults['global_sel_fill'][7:9]
  2646. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2647. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2648. def on_sf_color_button(self):
  2649. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2650. c_dialog = QtWidgets.QColorDialog()
  2651. plot_fill_color = c_dialog.getColor(initial=current_color)
  2652. if plot_fill_color.isValid() is False:
  2653. return
  2654. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2655. "background-color:%s" % str(plot_fill_color.name()))
  2656. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2657. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2658. self.defaults['global_sel_fill'] = new_val
  2659. def on_sf_color_spinner(self):
  2660. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2661. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2662. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2663. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2664. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2665. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2666. def on_sf_color_slider(self):
  2667. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2668. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2669. def on_sl_color_entry(self):
  2670. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2671. self.defaults['global_sel_line'][7:9]
  2672. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2673. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2674. def on_sl_color_button(self):
  2675. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2676. c_dialog = QtWidgets.QColorDialog()
  2677. plot_line_color = c_dialog.getColor(initial=current_color)
  2678. if plot_line_color.isValid() is False:
  2679. return
  2680. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2681. "background-color:%s" % str(plot_line_color.name()))
  2682. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2683. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2684. self.defaults['global_sel_line'] = new_val_line
  2685. # Setting selection colors (right - left) handlers
  2686. def on_alt_sf_color_entry(self):
  2687. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2688. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2689. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2690. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2691. def on_alt_sf_color_button(self):
  2692. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2693. c_dialog = QtWidgets.QColorDialog()
  2694. plot_fill_color = c_dialog.getColor(initial=current_color)
  2695. if plot_fill_color.isValid() is False:
  2696. return
  2697. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2698. "background-color:%s" % str(plot_fill_color.name()))
  2699. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2700. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2701. self.defaults['global_alt_sel_fill'] = new_val
  2702. def on_alt_sf_color_spinner(self):
  2703. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2704. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2705. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2706. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2707. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2708. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2709. def on_alt_sf_color_slider(self):
  2710. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2711. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2712. def on_alt_sl_color_entry(self):
  2713. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2714. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2715. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2716. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2717. def on_alt_sl_color_button(self):
  2718. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2719. c_dialog = QtWidgets.QColorDialog()
  2720. plot_line_color = c_dialog.getColor(initial=current_color)
  2721. if plot_line_color.isValid() is False:
  2722. return
  2723. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2724. "background-color:%s" % str(plot_line_color.name()))
  2725. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2726. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2727. self.defaults['global_alt_sel_line'] = new_val_line
  2728. # Setting Editor colors
  2729. def on_draw_color_entry(self):
  2730. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2731. .draw_color_entry.get_value()
  2732. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2733. "background-color:%s" % str(self.defaults['global_draw_color']))
  2734. def on_draw_color_button(self):
  2735. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2736. c_dialog = QtWidgets.QColorDialog()
  2737. draw_color = c_dialog.getColor(initial=current_color)
  2738. if draw_color.isValid() is False:
  2739. return
  2740. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2741. "background-color:%s" % str(draw_color.name()))
  2742. new_val = str(draw_color.name())
  2743. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2744. self.defaults['global_draw_color'] = new_val
  2745. def on_sel_draw_color_entry(self):
  2746. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2747. .sel_draw_color_entry.get_value()
  2748. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2749. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2750. def on_sel_draw_color_button(self):
  2751. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2752. c_dialog = QtWidgets.QColorDialog()
  2753. sel_draw_color = c_dialog.getColor(initial=current_color)
  2754. if sel_draw_color.isValid() is False:
  2755. return
  2756. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2757. "background-color:%s" % str(sel_draw_color.name()))
  2758. new_val_sel = str(sel_draw_color.name())
  2759. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2760. self.defaults['global_sel_draw_color'] = new_val_sel
  2761. def on_deselect_all(self):
  2762. self.collection.set_all_inactive()
  2763. self.delete_selection_shape()
  2764. def on_workspace_modified(self):
  2765. self.save_defaults(silent=True)
  2766. self.plotcanvas.draw_workspace()
  2767. def on_workspace(self):
  2768. self.report_usage("on_workspace()")
  2769. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2770. self.plotcanvas.restore_workspace()
  2771. else:
  2772. self.plotcanvas.delete_workspace()
  2773. self.save_defaults(silent=True)
  2774. def on_workspace_menu(self):
  2775. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2776. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2777. else:
  2778. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2779. self.on_workspace()
  2780. def on_layout(self, index, lay=None):
  2781. self.report_usage("on_layout()")
  2782. if lay:
  2783. current_layout = lay
  2784. else:
  2785. current_layout = self.general_defaults_form.general_gui_set_group.layout_combo.get_value().lower()
  2786. settings = QSettings("Open Source", "FlatCAM")
  2787. settings.setValue('layout', current_layout)
  2788. # This will write the setting to the platform specific storage.
  2789. del settings
  2790. # first remove the toolbars:
  2791. self.ui.removeToolBar(self.ui.toolbarfile)
  2792. self.ui.removeToolBar(self.ui.toolbargeo)
  2793. self.ui.removeToolBar(self.ui.toolbarview)
  2794. self.ui.removeToolBar(self.ui.toolbartools)
  2795. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2796. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2797. self.ui.removeToolBar(self.ui.snap_toolbar)
  2798. if current_layout == 'standard':
  2799. ### TOOLBAR INSTALLATION ###
  2800. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2801. self.ui.toolbarfile.setObjectName('File_TB')
  2802. self.ui.addToolBar(self.ui.toolbarfile)
  2803. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2804. self.ui.toolbargeo.setObjectName('Edit_TB')
  2805. self.ui.addToolBar(self.ui.toolbargeo)
  2806. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2807. self.ui.toolbarview.setObjectName('View_TB')
  2808. self.ui.addToolBar(self.ui.toolbarview)
  2809. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2810. self.ui.toolbartools.setObjectName('Tools_TB')
  2811. self.ui.addToolBar(self.ui.toolbartools)
  2812. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2813. self.ui.exc_edit_toolbar.setVisible(False)
  2814. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2815. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2816. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2817. self.ui.geo_edit_toolbar.setVisible(False)
  2818. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2819. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2820. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2821. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2822. # self.ui.snap_toolbar.setMaximumHeight(30)
  2823. self.ui.addToolBar(self.ui.snap_toolbar)
  2824. self.ui.corner_snap_btn.setVisible(False)
  2825. self.ui.snap_magnet.setVisible(False)
  2826. elif current_layout == 'compact':
  2827. ### TOOLBAR INSTALLATION ###
  2828. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2829. self.ui.toolbarfile.setObjectName('File_TB')
  2830. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2831. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2832. self.ui.toolbargeo.setObjectName('Edit_TB')
  2833. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2834. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2835. self.ui.toolbarview.setObjectName('View_TB')
  2836. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2837. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2838. self.ui.toolbartools.setObjectName('Tools_TB')
  2839. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2840. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2841. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2842. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2843. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2844. self.ui.geo_edit_toolbar.setVisible(False)
  2845. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2846. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2847. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2848. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2849. self.ui.snap_toolbar.setMaximumHeight(30)
  2850. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2851. self.ui.corner_snap_btn.setVisible(True)
  2852. self.ui.snap_magnet.setVisible(True)
  2853. self.ui.populate_toolbars()
  2854. self.ui.grid_snap_btn.setChecked(True)
  2855. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2856. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2857. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2858. self.ui.grid_gap_link_cb.setChecked(True)
  2859. def on_save_button(self):
  2860. self.save_defaults(silent=False)
  2861. # load the defaults so they are updated into the app
  2862. self.load_defaults(filename='current_defaults')
  2863. # Re-fresh project options
  2864. self.on_options_app2project()
  2865. def handleOpen(self):
  2866. self.report_usage("handleOpen()")
  2867. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2868. "All Files (*.*)"
  2869. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2870. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2871. if path:
  2872. file = QtCore.QFile(path)
  2873. if file.open(QtCore.QIODevice.ReadOnly):
  2874. stream = QtCore.QTextStream(file)
  2875. self.gcode_edited = stream.readAll()
  2876. self.ui.code_editor.setPlainText(self.gcode_edited)
  2877. file.close()
  2878. def handlePrint(self):
  2879. self.report_usage("handlePrint()")
  2880. dialog = QtPrintSupport.QPrintDialog()
  2881. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2882. self.ui.code_editor.document().print_(dialog.printer())
  2883. def handlePreview(self):
  2884. self.report_usage("handlePreview()")
  2885. dialog = QtPrintSupport.QPrintPreviewDialog()
  2886. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2887. dialog.exec_()
  2888. def handleTextChanged(self):
  2889. self.report_usage("handleTextChanged()")
  2890. # enable = not self.ui.code_editor.document().isEmpty()
  2891. # self.ui.buttonPrint.setEnabled(enable)
  2892. # self.ui.buttonPreview.setEnabled(enable)
  2893. pass
  2894. def handleSaveGCode(self):
  2895. self.report_usage("handleSaveGCode()")
  2896. obj_name = self.collection.get_active().options['name']
  2897. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2898. "All Files (*.*)"
  2899. try:
  2900. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2901. caption="Export G-Code ...",
  2902. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2903. filter=_filter_
  2904. )[0])
  2905. except TypeError:
  2906. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2907. if filename == "":
  2908. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2909. return
  2910. else:
  2911. try:
  2912. my_gcode = self.ui.code_editor.toPlainText()
  2913. with open(filename, 'w') as f:
  2914. for line in my_gcode:
  2915. f.write(line)
  2916. except FileNotFoundError:
  2917. self.inform.emit("[WARNING] No such file or directory")
  2918. return
  2919. # Just for adding it to the recent files list.
  2920. self.file_opened.emit("cncjob", filename)
  2921. self.file_saved.emit("cncjob", filename)
  2922. self.inform.emit("Saved to: " + filename)
  2923. def handleFindGCode(self):
  2924. self.report_usage("handleFindGCode()")
  2925. flags = QtGui.QTextDocument.FindCaseSensitively
  2926. text_to_be_found = self.ui.entryFind.get_value()
  2927. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2928. if r is False:
  2929. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2930. def handleReplaceGCode(self):
  2931. self.report_usage("handleReplaceGCode()")
  2932. old = self.ui.entryFind.get_value()
  2933. new = self.ui.entryReplace.get_value()
  2934. if self.ui.sel_all_cb.isChecked():
  2935. while True:
  2936. cursor = self.ui.code_editor.textCursor()
  2937. cursor.beginEditBlock()
  2938. flags = QtGui.QTextDocument.FindCaseSensitively
  2939. # self.ui.editor is the QPlainTextEdit
  2940. r = self.ui.code_editor.find(str(old), flags)
  2941. if r:
  2942. qc = self.ui.code_editor.textCursor()
  2943. if qc.hasSelection():
  2944. qc.insertText(new)
  2945. else:
  2946. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2947. break
  2948. # Mark end of undo block
  2949. cursor.endEditBlock()
  2950. else:
  2951. cursor = self.ui.code_editor.textCursor()
  2952. cursor.beginEditBlock()
  2953. qc = self.ui.code_editor.textCursor()
  2954. if qc.hasSelection():
  2955. qc.insertText(new)
  2956. # Mark end of undo block
  2957. cursor.endEditBlock()
  2958. def on_tool_add_keypress(self):
  2959. ## Current application units in Upper Case
  2960. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2961. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2962. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2963. if notebook_widget_name == 'selected_tab':
  2964. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2965. # Tool add works for Geometry only if Advanced is True in Preferences
  2966. if self.defaults["global_advanced"] is True:
  2967. tool_add_popup = FCInputDialog(title="New Tool ...",
  2968. text='Enter a Tool Diameter:',
  2969. min=0.0000, max=99.9999, decimals=4)
  2970. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2971. val, ok = tool_add_popup.get_value()
  2972. if ok:
  2973. if float(val) == 0:
  2974. self.inform.emit(
  2975. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2976. return
  2977. self.collection.get_active().on_tool_add(dia=float(val))
  2978. else:
  2979. self.inform.emit(
  2980. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2981. else:
  2982. msgbox = QtWidgets.QMessageBox()
  2983. msgbox.setText("Adding Tool works only when Advanced is checked.\n"
  2984. "Go to Preferences -> General - Show Advanced Options.")
  2985. msgbox.setWindowTitle("Tool adding ...")
  2986. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2987. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2988. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2989. msgbox.exec_()
  2990. # work only if the notebook tab on focus is the Tools_Tab
  2991. if notebook_widget_name == 'tool_tab':
  2992. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2993. # and only if the tool is NCC Tool
  2994. if tool_widget == self.ncclear_tool.toolName:
  2995. tool_add_popup = FCInputDialog(title="New Tool ...",
  2996. text='Enter a Tool Diameter:',
  2997. min=0.0000, max=99.9999, decimals=4)
  2998. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2999. val, ok = tool_add_popup.get_value()
  3000. if ok:
  3001. if float(val) == 0:
  3002. self.inform.emit(
  3003. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3004. return
  3005. self.ncclear_tool.on_tool_add(dia=float(val))
  3006. else:
  3007. self.inform.emit(
  3008. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3009. # and only if the tool is Paint Area Tool
  3010. elif tool_widget == self.paint_tool.toolName:
  3011. tool_add_popup = FCInputDialog(title="New Tool ...",
  3012. text='Enter a Tool Diameter:',
  3013. min=0.0000, max=99.9999, decimals=4)
  3014. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3015. val, ok = tool_add_popup.get_value()
  3016. if ok:
  3017. if float(val) == 0:
  3018. self.inform.emit(
  3019. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3020. return
  3021. self.paint_tool.on_tool_add(dia=float(val))
  3022. else:
  3023. self.inform.emit(
  3024. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3025. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3026. # See description bellow.
  3027. def on_delete_keypress(self):
  3028. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3029. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3030. if notebook_widget_name == 'selected_tab':
  3031. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3032. self.collection.get_active().on_tool_delete()
  3033. # work only if the notebook tab on focus is the Tools_Tab
  3034. elif notebook_widget_name == 'tool_tab':
  3035. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3036. # and only if the tool is NCC Tool
  3037. if tool_widget == self.ncclear_tool.toolName:
  3038. self.ncclear_tool.on_tool_delete()
  3039. # and only if the tool is Paint Tool
  3040. elif tool_widget == self.paint_tool.toolName:
  3041. self.paint_tool.on_tool_delete()
  3042. else:
  3043. self.on_delete()
  3044. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3045. # some screens you have to be careful where you hover with your mouse.
  3046. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3047. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3048. # Complicated, I know :)
  3049. def on_delete(self):
  3050. """
  3051. Delete the currently selected FlatCAMObjs.
  3052. :return: None
  3053. """
  3054. self.report_usage("on_delete()")
  3055. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3056. # a geometry object before we update it.
  3057. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3058. if self.collection.get_active():
  3059. self.log.debug("on_delete()")
  3060. self.report_usage("on_delete")
  3061. while (self.collection.get_active()):
  3062. self.delete_first_selected()
  3063. self.inform.emit("Object(s) deleted ...")
  3064. # make sure that the selection shape is deleted, too
  3065. self.delete_selection_shape()
  3066. else:
  3067. self.inform.emit("Failed. No object(s) selected...")
  3068. else:
  3069. self.inform.emit("Save the work in Editor and try again ...")
  3070. def on_set_origin(self):
  3071. """
  3072. Set the origin to the left mouse click position
  3073. :return: None
  3074. """
  3075. #display the message for the user
  3076. #and ask him to click on the desired position
  3077. self.report_usage("on_set_origin()")
  3078. self.inform.emit('Click to set the origin ...')
  3079. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3080. def on_jump_to(self):
  3081. """
  3082. Jump to a location by setting the mouse cursor location
  3083. :return:
  3084. """
  3085. self.report_usage("on_jump_to()")
  3086. dia_box = Dialog_box(title="Jump to ...",
  3087. label="Enter the coordinates in format X,Y:",
  3088. icon=QtGui.QIcon('share/jump_to16.png'))
  3089. if dia_box.ok is True:
  3090. try:
  3091. location = eval(dia_box.location)
  3092. if not isinstance(location, tuple):
  3093. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3094. return
  3095. except:
  3096. return
  3097. else:
  3098. return
  3099. self.plotcanvas.fit_center(loc=location)
  3100. cursor = QtGui.QCursor()
  3101. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3102. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3103. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3104. self.inform.emit("Done.")
  3105. def on_copy_object(self):
  3106. self.report_usage("on_copy_object()")
  3107. def initialize(obj_init, app):
  3108. obj_init.solid_geometry = obj.solid_geometry
  3109. try:
  3110. if obj.tools:
  3111. obj_init.tools = obj.tools
  3112. except Exception as e:
  3113. log.debug("on_copy_object() --> %s" % str(e))
  3114. def initialize_excellon(obj_init, app):
  3115. obj_init.tools = obj.tools
  3116. # drills are offset, so they need to be deep copied
  3117. obj_init.drills = deepcopy(obj.drills)
  3118. # slots are offset, so they need to be deep copied
  3119. obj_init.slots = deepcopy(obj.slots)
  3120. obj_init.create_geometry()
  3121. for obj in self.collection.get_selected():
  3122. obj_name = obj.options["name"]
  3123. try:
  3124. if isinstance(obj, FlatCAMExcellon):
  3125. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3126. elif isinstance(obj,FlatCAMGerber):
  3127. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3128. elif isinstance(obj,FlatCAMGeometry):
  3129. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3130. except Exception as e:
  3131. return "Operation failed: %s" % str(e)
  3132. def on_copy_object2(self, custom_name):
  3133. def initialize_geometry(obj_init, app):
  3134. obj_init.solid_geometry = obj.solid_geometry
  3135. try:
  3136. if obj.tools:
  3137. obj_init.tools = obj.tools
  3138. except Exception as e:
  3139. log.debug("on_copy_object2() --> %s" % str(e))
  3140. def initialize_gerber(obj_init, app):
  3141. obj_init.solid_geometry = obj.solid_geometry
  3142. obj_init.apertures = deepcopy(obj.apertures)
  3143. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3144. def initialize_excellon(obj_init, app):
  3145. obj_init.tools = obj.tools
  3146. # drills are offset, so they need to be deep copied
  3147. obj_init.drills = deepcopy(obj.drills)
  3148. # slots are offset, so they need to be deep copied
  3149. obj_init.slots = deepcopy(obj.slots)
  3150. obj_init.create_geometry()
  3151. for obj in self.collection.get_selected():
  3152. obj_name = obj.options["name"]
  3153. try:
  3154. if isinstance(obj, FlatCAMExcellon):
  3155. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3156. elif isinstance(obj,FlatCAMGerber):
  3157. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3158. elif isinstance(obj,FlatCAMGeometry):
  3159. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3160. except Exception as e:
  3161. return "Operation failed: %s" % str(e)
  3162. def on_rename_object(self, text):
  3163. self.report_usage("on_rename_object()")
  3164. named_obj = self.collection.get_active()
  3165. for obj in named_obj:
  3166. if obj is list:
  3167. self.on_rename_object(text)
  3168. else:
  3169. try:
  3170. obj.options['name'] = text
  3171. except:
  3172. log.warning("Could not rename the object in the list")
  3173. def on_copy_object_as_geometry(self):
  3174. self.report_usage("on_copy_object_as_geometry()")
  3175. def initialize(obj_init, app):
  3176. obj_init.solid_geometry = obj.solid_geometry
  3177. if obj.tools:
  3178. obj_init.tools = obj.tools
  3179. def initialize_excellon(obj, app):
  3180. objs = self.collection.get_selected()
  3181. FlatCAMGeometry.merge(objs, obj)
  3182. for obj in self.collection.get_selected():
  3183. obj_name = obj.options["name"]
  3184. try:
  3185. if isinstance(obj, FlatCAMExcellon):
  3186. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3187. else:
  3188. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3189. except Exception as e:
  3190. return "Operation failed: %s" % str(e)
  3191. def on_set_zero_click(self, event):
  3192. #this function will be available only for mouse left click
  3193. pos =[]
  3194. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3195. if event.button == 1:
  3196. if self.grid_status() == True:
  3197. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3198. else:
  3199. pos = pos_canvas
  3200. x = 0 - pos[0]
  3201. y = 0 - pos[1]
  3202. for obj in self.collection.get_list():
  3203. obj.offset((x,y))
  3204. self.object_changed.emit(obj)
  3205. # obj.plot()
  3206. self.plot_all(zoom=False)
  3207. self.inform.emit('[success] Origin set ...')
  3208. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3209. self.should_we_save = True
  3210. def on_selectall(self):
  3211. self.report_usage("on_selectall()")
  3212. # delete the possible selection box around a possible selected object
  3213. self.delete_selection_shape()
  3214. for name in self.collection.get_names():
  3215. self.collection.set_active(name)
  3216. curr_sel_obj = self.collection.get_by_name(name)
  3217. # create the selection box around the selected object
  3218. self.draw_selection_shape(curr_sel_obj)
  3219. def on_preferences(self):
  3220. # add the tab if it was closed
  3221. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3222. # delete the absolute and relative position and messages in the infobar
  3223. self.ui.position_label.setText("")
  3224. self.ui.rel_position_label.setText("")
  3225. # Switch plot_area to preferences page
  3226. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3227. self.ui.show()
  3228. def on_flipy(self):
  3229. self.report_usage("on_flipy()")
  3230. obj_list = self.collection.get_selected()
  3231. xminlist = []
  3232. yminlist = []
  3233. xmaxlist = []
  3234. ymaxlist = []
  3235. if not obj_list:
  3236. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3237. else:
  3238. try:
  3239. # first get a bounding box to fit all
  3240. for obj in obj_list:
  3241. xmin, ymin, xmax, ymax = obj.bounds()
  3242. xminlist.append(xmin)
  3243. yminlist.append(ymin)
  3244. xmaxlist.append(xmax)
  3245. ymaxlist.append(ymax)
  3246. # get the minimum x,y and maximum x,y for all objects selected
  3247. xminimal = min(xminlist)
  3248. yminimal = min(yminlist)
  3249. xmaximal = max(xmaxlist)
  3250. ymaximal = max(ymaxlist)
  3251. px = 0.5 * (xminimal + xmaximal)
  3252. py = 0.5 * (yminimal + ymaximal)
  3253. # execute mirroring
  3254. for obj in obj_list:
  3255. obj.mirror('X', [px, py])
  3256. obj.plot()
  3257. self.object_changed.emit(obj)
  3258. self.inform.emit("[success] Flip on Y axis done.")
  3259. except Exception as e:
  3260. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3261. return
  3262. def on_flipx(self):
  3263. self.report_usage("on_flipx()")
  3264. obj_list = self.collection.get_selected()
  3265. xminlist = []
  3266. yminlist = []
  3267. xmaxlist = []
  3268. ymaxlist = []
  3269. if not obj_list:
  3270. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3271. else:
  3272. try:
  3273. # first get a bounding box to fit all
  3274. for obj in obj_list:
  3275. xmin, ymin, xmax, ymax = obj.bounds()
  3276. xminlist.append(xmin)
  3277. yminlist.append(ymin)
  3278. xmaxlist.append(xmax)
  3279. ymaxlist.append(ymax)
  3280. # get the minimum x,y and maximum x,y for all objects selected
  3281. xminimal = min(xminlist)
  3282. yminimal = min(yminlist)
  3283. xmaximal = max(xmaxlist)
  3284. ymaximal = max(ymaxlist)
  3285. px = 0.5 * (xminimal + xmaximal)
  3286. py = 0.5 * (yminimal + ymaximal)
  3287. # execute mirroring
  3288. for obj in obj_list:
  3289. obj.mirror('Y', [px, py])
  3290. obj.plot()
  3291. self.object_changed.emit(obj)
  3292. self.inform.emit("[success] Flip on X axis done.")
  3293. except Exception as e:
  3294. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3295. return
  3296. def on_rotate(self, silent=False, preset=None):
  3297. self.report_usage("on_rotate()")
  3298. obj_list = self.collection.get_selected()
  3299. xminlist = []
  3300. yminlist = []
  3301. xmaxlist = []
  3302. ymaxlist = []
  3303. if not obj_list:
  3304. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3305. else:
  3306. if silent is False:
  3307. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3308. min=-360, max=360, decimals=4,
  3309. init_val=float(self.defaults['tools_transform_rotate']))
  3310. num, ok = rotatebox.get_value()
  3311. else:
  3312. num = preset
  3313. ok = True
  3314. if ok:
  3315. try:
  3316. # first get a bounding box to fit all
  3317. for obj in obj_list:
  3318. xmin, ymin, xmax, ymax = obj.bounds()
  3319. xminlist.append(xmin)
  3320. yminlist.append(ymin)
  3321. xmaxlist.append(xmax)
  3322. ymaxlist.append(ymax)
  3323. # get the minimum x,y and maximum x,y for all objects selected
  3324. xminimal = min(xminlist)
  3325. yminimal = min(yminlist)
  3326. xmaximal = max(xmaxlist)
  3327. ymaximal = max(ymaxlist)
  3328. px = 0.5 * (xminimal + xmaximal)
  3329. py = 0.5 * (yminimal + ymaximal)
  3330. for sel_obj in obj_list:
  3331. sel_obj.rotate(-num, point=(px, py))
  3332. sel_obj.plot()
  3333. self.object_changed.emit(sel_obj)
  3334. self.inform.emit("[success] Rotation done.")
  3335. except Exception as e:
  3336. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3337. return
  3338. def on_skewx(self):
  3339. self.report_usage("on_skewx()")
  3340. obj_list = self.collection.get_selected()
  3341. xminlist = []
  3342. yminlist = []
  3343. if not obj_list:
  3344. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3345. else:
  3346. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3347. min=-360, max=360, decimals=4,
  3348. init_val=float(self.defaults['tools_transform_skew_x']))
  3349. num, ok = skewxbox.get_value()
  3350. if ok:
  3351. # first get a bounding box to fit all
  3352. for obj in obj_list:
  3353. xmin, ymin, xmax, ymax = obj.bounds()
  3354. xminlist.append(xmin)
  3355. yminlist.append(ymin)
  3356. # get the minimum x,y and maximum x,y for all objects selected
  3357. xminimal = min(xminlist)
  3358. yminimal = min(yminlist)
  3359. for obj in obj_list:
  3360. obj.skew(num, 0, point=(xminimal, yminimal))
  3361. obj.plot()
  3362. self.object_changed.emit(obj)
  3363. self.inform.emit("[success] Skew on X axis done.")
  3364. def on_skewy(self):
  3365. self.report_usage("on_skewy()")
  3366. obj_list = self.collection.get_selected()
  3367. xminlist = []
  3368. yminlist = []
  3369. if not obj_list:
  3370. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3371. else:
  3372. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3373. min=-360, max=360, decimals=4,
  3374. init_val=float(self.defaults['tools_transform_skew_y']))
  3375. num, ok = skewybox.get_value()
  3376. if ok:
  3377. # first get a bounding box to fit all
  3378. for obj in obj_list:
  3379. xmin, ymin, xmax, ymax = obj.bounds()
  3380. xminlist.append(xmin)
  3381. yminlist.append(ymin)
  3382. # get the minimum x,y and maximum x,y for all objects selected
  3383. xminimal = min(xminlist)
  3384. yminimal = min(yminlist)
  3385. for obj in obj_list:
  3386. obj.skew(0, num, point=(xminimal, yminimal))
  3387. obj.plot()
  3388. self.object_changed.emit(obj)
  3389. self.inform.emit("[success] Skew on Y axis done.")
  3390. def delete_first_selected(self):
  3391. # Keep this for later
  3392. try:
  3393. name = self.collection.get_active().options["name"]
  3394. except AttributeError:
  3395. self.log.debug("Nothing selected for deletion")
  3396. return
  3397. # Remove plot
  3398. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3399. # self.plotcanvas.auto_adjust_axes()
  3400. # Clear form
  3401. self.setup_component_editor()
  3402. # Remove from dictionary
  3403. self.collection.delete_active()
  3404. self.inform.emit("Object deleted: %s" % name)
  3405. def on_plots_updated(self):
  3406. """
  3407. Callback used to report when the plots have changed.
  3408. Adjust axes and zooms to fit.
  3409. :return: None
  3410. """
  3411. # self.plotcanvas.auto_adjust_axes()
  3412. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3413. self.on_zoom_fit(None)
  3414. # TODO: Rework toolbar 'clear', 'replot' functions
  3415. def on_toolbar_replot(self):
  3416. """
  3417. Callback for toolbar button. Re-plots all objects.
  3418. :return: None
  3419. """
  3420. self.report_usage("on_toolbar_replot")
  3421. self.log.debug("on_toolbar_replot()")
  3422. try:
  3423. self.collection.get_active().read_form()
  3424. except AttributeError:
  3425. self.log.debug("on_toolbar_replot(): AttributeError")
  3426. pass
  3427. self.plot_all()
  3428. def on_row_activated(self, index):
  3429. if index.isValid():
  3430. if index.internalPointer().parent_item != self.collection.root_item:
  3431. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3432. def grid_status(self):
  3433. if self.ui.grid_snap_btn.isChecked():
  3434. return 1
  3435. else:
  3436. return 0
  3437. def populate_cmenu_grids(self):
  3438. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3439. self.ui.cmenu_gridmenu.clear()
  3440. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3441. for grid in sorted_list:
  3442. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3443. action.triggered.connect(self.set_grid)
  3444. self.ui.cmenu_gridmenu.addSeparator()
  3445. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3446. grid_add.triggered.connect(self.on_grid_add)
  3447. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3448. grid_delete.triggered.connect(self.on_grid_delete)
  3449. def set_grid(self):
  3450. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3451. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3452. def on_grid_add(self):
  3453. ## Current application units in lower Case
  3454. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3455. grid_add_popup = FCInputDialog(title="New Grid ...",
  3456. text='Enter a Grid VAlue:',
  3457. min=0.0000, max=99.9999, decimals=4)
  3458. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3459. val, ok = grid_add_popup.get_value()
  3460. if ok:
  3461. if float(val) == 0:
  3462. self.inform.emit(
  3463. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3464. return
  3465. else:
  3466. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3467. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3468. self.inform.emit(
  3469. "[success] New Grid added ...")
  3470. else:
  3471. self.inform.emit(
  3472. "[WARNING_NOTCL] Grid already exists ...")
  3473. else:
  3474. self.inform.emit(
  3475. "[WARNING_NOTCL] Adding New Grid cancelled ...")
  3476. def on_grid_delete(self):
  3477. ## Current application units in lower Case
  3478. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3479. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3480. text='Enter a Grid Value:',
  3481. min=0.0000, max=99.9999, decimals=4)
  3482. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3483. val, ok = grid_del_popup.get_value()
  3484. if ok:
  3485. if float(val) == 0:
  3486. self.inform.emit(
  3487. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3488. return
  3489. else:
  3490. try:
  3491. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3492. except ValueError:
  3493. self.inform.emit(
  3494. "[ERROR_NOTCL] Grid Value does not exist ...")
  3495. return
  3496. self.inform.emit(
  3497. "[success] Grid Value deleted ...")
  3498. else:
  3499. self.inform.emit(
  3500. "[WARNING_NOTCL] Delete Grid value cancelled ...")
  3501. def on_shortcut_list(self):
  3502. self.report_usage("on_shortcut_list()")
  3503. # add the tab if it was closed
  3504. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3505. # delete the absolute and relative position and messages in the infobar
  3506. self.ui.position_label.setText("")
  3507. self.ui.rel_position_label.setText("")
  3508. # Switch plot_area to preferences page
  3509. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3510. self.ui.show()
  3511. def on_select_tab(self, name):
  3512. if name == 'project':
  3513. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3514. elif name == 'selected':
  3515. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3516. elif name == 'tool':
  3517. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3518. # if the splitter us hidden, display it
  3519. if self.ui.splitter.sizes()[0] == 0:
  3520. self.ui.splitter.setSizes([1, 1])
  3521. def on_copy_name(self):
  3522. self.report_usage("on_copy_name()")
  3523. obj = self.collection.get_active()
  3524. try:
  3525. name = obj.options["name"]
  3526. except AttributeError:
  3527. log.debug("on_copy_name() --> No object selected to copy it's name")
  3528. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3529. return
  3530. self.clipboard.setText(name)
  3531. self.inform.emit("Name copied on clipboard ...")
  3532. def on_mouse_click_over_plot(self, event):
  3533. """
  3534. Callback for the mouse click event over the plot. This event is generated
  3535. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3536. For details, see: http://matplotlib.org/users/event_handling.html
  3537. Default actions are:
  3538. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3539. :param event: Contains information about the event, like which button
  3540. was clicked, the pixel coordinates and the axes coordinates.
  3541. :return: None
  3542. """
  3543. self.pos = []
  3544. # So it can receive key presses
  3545. self.plotcanvas.vispy_canvas.native.setFocus()
  3546. # Set the mouse button for panning
  3547. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3548. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3549. if self.grid_status() == True:
  3550. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3551. self.app_cursor.enabled = True
  3552. else:
  3553. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3554. self.app_cursor.enabled = False
  3555. try:
  3556. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3557. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3558. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3559. if event.button == 1:
  3560. # Reset here the relative coordinates so there is a new reference on the click position
  3561. if self.rel_point1 is None:
  3562. self.rel_point1 = self.pos
  3563. else:
  3564. self.rel_point2 = copy(self.rel_point1)
  3565. self.rel_point1 = self.pos
  3566. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3567. if modifiers == QtCore.Qt.ShiftModifier:
  3568. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3569. return
  3570. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3571. # and if it's not selected then it will be selected
  3572. if modifiers == QtCore.Qt.ControlModifier:
  3573. # If there is no active command (self.command_active is None) then we check if we clicked on
  3574. # a object by checking the bounding limits against mouse click position
  3575. if self.command_active is None:
  3576. self.select_objects(key='CTRL')
  3577. else:
  3578. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3579. # checking the bounding limits against mouse click position
  3580. if self.command_active is None:
  3581. self.select_objects()
  3582. self.on_mouse_move_over_plot(event, origin_click=True)
  3583. except Exception as e:
  3584. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3585. def on_double_click_over_plot(self, event):
  3586. # make double click work only for the LMB
  3587. if event.button == 1:
  3588. if self.collection.get_selected():
  3589. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3590. # delete the selection shape(S) as it may be in the way
  3591. self.delete_selection_shape()
  3592. def on_mouse_move_over_plot(self, event, origin_click=None):
  3593. """
  3594. Callback for the mouse motion event over the plot. This event is generated
  3595. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3596. For details, see: http://matplotlib.org/users/event_handling.html
  3597. :param event: Contains information about the event.
  3598. :param origin_click
  3599. :return: None
  3600. """
  3601. # So it can receive key presses
  3602. self.plotcanvas.vispy_canvas.native.setFocus()
  3603. self.pos_jump = event.pos
  3604. if origin_click is True:
  3605. pass
  3606. else:
  3607. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3608. if event.button == 2:
  3609. self.panning_action = True
  3610. return
  3611. else:
  3612. self.panning_action = False
  3613. if self.rel_point1 is not None:
  3614. try: # May fail in case mouse not within axes
  3615. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3616. if self.grid_status():
  3617. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3618. self.app_cursor.enabled = True
  3619. # Update cursor
  3620. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3621. else:
  3622. pos = (pos_canvas[0], pos_canvas[1])
  3623. self.app_cursor.enabled = False
  3624. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3625. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3626. dx = pos[0] - self.rel_point1[0]
  3627. dy = pos[1] - self.rel_point1[1]
  3628. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3629. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3630. self.mouse = [pos[0], pos[1]]
  3631. # if the mouse is moved and the LMB is clicked then the action is a selection
  3632. if event.is_dragging == 1 and event.button == 1:
  3633. self.delete_selection_shape()
  3634. if dx < 0:
  3635. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3636. face_color=self.defaults['global_alt_sel_fill'])
  3637. self.selection_type = False
  3638. else:
  3639. self.draw_moving_selection_shape(self.pos, pos)
  3640. self.selection_type = True
  3641. # delete the status message on mouse move
  3642. # self.inform.emit("")
  3643. except:
  3644. self.ui.position_label.setText("")
  3645. self.ui.rel_position_label.setText("")
  3646. self.mouse = None
  3647. def on_mouse_click_release_over_plot(self, event):
  3648. """
  3649. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3650. and has been registered in ''self.__init__()''.
  3651. :param event: contains information about the event.
  3652. :return:
  3653. """
  3654. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3655. if self.grid_status():
  3656. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3657. else:
  3658. pos = (pos_canvas[0], pos_canvas[1])
  3659. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3660. # canvas menu
  3661. try:
  3662. if event.button == 2: # right click
  3663. if self.panning_action is True:
  3664. self.panning_action = False
  3665. else:
  3666. self.cursor = QtGui.QCursor()
  3667. self.populate_cmenu_grids()
  3668. self.ui.popMenu.popup(self.cursor.pos())
  3669. except Exception as e:
  3670. log.warning("Error: %s" % str(e))
  3671. return
  3672. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3673. # selection and then select a type of selection ("enclosing" or "touching")
  3674. try:
  3675. if event.button == 1: # left click
  3676. if self.selection_type is not None:
  3677. self.selection_area_handler(self.pos, pos, self.selection_type)
  3678. self.selection_type = None
  3679. except Exception as e:
  3680. log.warning("Error: %s" % str(e))
  3681. return
  3682. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3683. """
  3684. :param start_pos: mouse position when the selection LMB click was done
  3685. :param end_pos: mouse position when the left mouse button is released
  3686. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3687. :return:
  3688. """
  3689. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3690. self.delete_selection_shape()
  3691. for obj in self.collection.get_list():
  3692. try:
  3693. # select the object(s) only if it is enabled (plotted)
  3694. if obj.options['plot']:
  3695. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3696. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3697. if sel_type is True:
  3698. if poly_obj.within(poly_selection):
  3699. # create the selection box around the selected object
  3700. self.draw_selection_shape(obj)
  3701. self.collection.set_active(obj.options['name'])
  3702. else:
  3703. if poly_selection.intersects(poly_obj):
  3704. # create the selection box around the selected object
  3705. self.draw_selection_shape(obj)
  3706. self.collection.set_active(obj.options['name'])
  3707. except:
  3708. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3709. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3710. # In this case poly_obj creation (see above) will fail
  3711. pass
  3712. def select_objects(self, key=None):
  3713. # list where we store the overlapped objects under our mouse left click position
  3714. objects_under_the_click_list = []
  3715. # Populate the list with the overlapped objects on the click position
  3716. curr_x, curr_y = self.pos
  3717. for obj in self.all_objects_list:
  3718. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3719. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3720. if obj.options['name'] not in objects_under_the_click_list:
  3721. if obj.options['plot']:
  3722. # add objects to the objects_under_the_click list only if the object is plotted
  3723. # (active and not disabled)
  3724. objects_under_the_click_list.append(obj.options['name'])
  3725. try:
  3726. # If there is no element in the overlapped objects list then make everyone inactive
  3727. # because we selected "nothing"
  3728. if not objects_under_the_click_list:
  3729. self.collection.set_all_inactive()
  3730. # delete the possible selection box around a possible selected object
  3731. self.delete_selection_shape()
  3732. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3733. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3734. # delete any text in the status bar, implicitly the last object name that was selected
  3735. self.inform.emit("")
  3736. else:
  3737. # case when there is only an object under the click and we toggle it
  3738. if len(objects_under_the_click_list) == 1:
  3739. if self.collection.get_active() is None :
  3740. self.collection.set_active(objects_under_the_click_list[0])
  3741. # create the selection box around the selected object
  3742. curr_sel_obj = self.collection.get_active()
  3743. self.draw_selection_shape(curr_sel_obj)
  3744. # self.inform.emit('[selected] %s: %s selected' %
  3745. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3746. if curr_sel_obj.kind == 'gerber':
  3747. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3748. ('green', str(curr_sel_obj.options['name'])))
  3749. elif curr_sel_obj.kind == 'excellon':
  3750. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3751. ('brown', str(curr_sel_obj.options['name'])))
  3752. elif curr_sel_obj.kind == 'cncjob':
  3753. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3754. ('blue', str(curr_sel_obj.options['name'])))
  3755. elif curr_sel_obj.kind == 'geometry':
  3756. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3757. ('red', str(curr_sel_obj.options['name'])))
  3758. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3759. self.collection.set_all_inactive()
  3760. self.delete_selection_shape()
  3761. self.collection.set_active(objects_under_the_click_list[0])
  3762. # create the selection box around the selected object
  3763. curr_sel_obj = self.collection.get_active()
  3764. self.draw_selection_shape(curr_sel_obj)
  3765. # self.inform.emit('[selected] %s: %s selected' %
  3766. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3767. if curr_sel_obj.kind == 'gerber':
  3768. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3769. ('green', str(curr_sel_obj.options['name'])))
  3770. elif curr_sel_obj.kind == 'excellon':
  3771. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3772. ('brown', str(curr_sel_obj.options['name'])))
  3773. elif curr_sel_obj.kind == 'cncjob':
  3774. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3775. ('blue', str(curr_sel_obj.options['name'])))
  3776. elif curr_sel_obj.kind == 'geometry':
  3777. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3778. ('red', str(curr_sel_obj.options['name'])))
  3779. else:
  3780. self.collection.set_all_inactive()
  3781. self.delete_selection_shape()
  3782. self.inform.emit("")
  3783. else:
  3784. # If there is no selected object
  3785. # make active the first element of the overlapped objects list
  3786. if self.collection.get_active() is None:
  3787. self.collection.set_active(objects_under_the_click_list[0])
  3788. name_sel_obj = self.collection.get_active().options['name']
  3789. # In case that there is a selected object but it is not in the overlapped object list
  3790. # make that object inactive and activate the first element in the overlapped object list
  3791. if name_sel_obj not in objects_under_the_click_list:
  3792. self.collection.set_inactive(name_sel_obj)
  3793. name_sel_obj = objects_under_the_click_list[0]
  3794. self.collection.set_active(name_sel_obj)
  3795. else:
  3796. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3797. self.collection.set_all_inactive()
  3798. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3799. len(objects_under_the_click_list)])
  3800. curr_sel_obj = self.collection.get_active()
  3801. # delete the possible selection box around a possible selected object
  3802. self.delete_selection_shape()
  3803. # create the selection box around the selected object
  3804. self.draw_selection_shape(curr_sel_obj)
  3805. # self.inform.emit('[selected] %s: %s selected' %
  3806. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3807. if curr_sel_obj.kind == 'gerber':
  3808. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3809. ('green', str(curr_sel_obj.options['name'])))
  3810. elif curr_sel_obj.kind == 'excellon':
  3811. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3812. ('brown', str(curr_sel_obj.options['name'])))
  3813. elif curr_sel_obj.kind == 'cncjob':
  3814. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3815. ('blue', str(curr_sel_obj.options['name'])))
  3816. elif curr_sel_obj.kind == 'geometry':
  3817. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3818. ('red', str(curr_sel_obj.options['name'])))
  3819. # for obj in self.collection.get_list():
  3820. # obj.plot()
  3821. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3822. # TODO: on selected objects change the object colors and do not draw the selection box
  3823. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3824. except Exception as e:
  3825. log.error("[ERROR] Something went bad. %s" % str(e))
  3826. return
  3827. def delete_selection_shape(self):
  3828. self.move_tool.sel_shapes.clear()
  3829. self.move_tool.sel_shapes.redraw()
  3830. def draw_selection_shape(self, sel_obj):
  3831. """
  3832. :param sel_obj: the object for which the selection shape must be drawn
  3833. :return:
  3834. """
  3835. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3836. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3837. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3838. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3839. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3840. #blue_t = Color('blue')
  3841. blue_t = Color(self.defaults['global_sel_fill'])
  3842. blue_t.alpha = 0.3
  3843. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3844. face_color=blue_t, update=True, layer=0, tolerance=None))
  3845. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3846. """
  3847. :param old_coords: old coordinates
  3848. :param coords: new coordinates
  3849. :return:
  3850. """
  3851. if 'color' in kwargs:
  3852. color = kwargs['color']
  3853. else:
  3854. color = self.defaults['global_sel_line']
  3855. if 'face_color' in kwargs:
  3856. face_color = kwargs['face_color']
  3857. else:
  3858. face_color = self.defaults['global_sel_fill']
  3859. x0, y0 = old_coords
  3860. x1, y1 = coords
  3861. pt1 = (x0, y0)
  3862. pt2 = (x1, y0)
  3863. pt3 = (x1, y1)
  3864. pt4 = (x0, y1)
  3865. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3866. color_t = Color(face_color)
  3867. color_t.alpha = 0.3
  3868. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3869. layer=0, tolerance=None)
  3870. def on_file_new_click(self):
  3871. if self.collection.get_list() and self.should_we_save:
  3872. msgbox = QtWidgets.QMessageBox()
  3873. # msgbox.setText("<B>Save changes ...</B>")
  3874. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3875. "Creating a New project will delete them.\n"
  3876. "Do you want to Save the project?")
  3877. msgbox.setWindowTitle("Save changes")
  3878. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3879. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3880. QtWidgets.QMessageBox.No)
  3881. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3882. response = msgbox.exec_()
  3883. if response == QtWidgets.QMessageBox.Yes:
  3884. self.on_file_saveprojectas()
  3885. elif response == QtWidgets.QMessageBox.Cancel:
  3886. return
  3887. self.on_file_new()
  3888. else:
  3889. self.on_file_new()
  3890. self.inform.emit("[success] New Project created...")
  3891. def on_file_new(self):
  3892. """
  3893. Callback for menu item File->New. Returns the application to its
  3894. startup state. This method is thread-safe.
  3895. :return: None
  3896. """
  3897. self.report_usage("on_file_new")
  3898. # Remove everything from memory
  3899. App.log.debug("on_file_new()")
  3900. # Clear pool
  3901. self.clear_pool()
  3902. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3903. self.init_tcl()
  3904. self.delete_selection_shape()
  3905. self.collection.delete_all()
  3906. self.setup_component_editor()
  3907. # Clear project filename
  3908. self.project_filename = None
  3909. # Load the application defaults
  3910. self.load_defaults(filename='current_defaults')
  3911. # Re-fresh project options
  3912. self.on_options_app2project()
  3913. # Init Tools
  3914. self.init_tools()
  3915. # take the focus of the Notebook on Project Tab.
  3916. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3917. def obj_properties(self):
  3918. self.report_usage("obj_properties()")
  3919. self.properties_tool.run()
  3920. def on_project_context_save(self):
  3921. obj = self.collection.get_active()
  3922. if type(obj) == FlatCAMGeometry:
  3923. self.on_file_exportdxf()
  3924. elif type(obj) == FlatCAMExcellon:
  3925. self.on_file_exportexcellon()
  3926. elif type(obj) == FlatCAMCNCjob:
  3927. obj.on_exportgcode_button_click()
  3928. elif type(obj) == FlatCAMGerber:
  3929. self.on_file_exportgerber()
  3930. def on_view_source(self):
  3931. try:
  3932. obj = self.collection.get_active()
  3933. except:
  3934. self.inform.emit("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source.")
  3935. # add the tab if it was closed
  3936. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  3937. # first clear previous text in text editor (if any)
  3938. self.ui.code_editor.clear()
  3939. # Switch plot_area to CNCJob tab
  3940. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  3941. # then append the text from GCode to the text editor
  3942. file = StringIO(obj.source_file)
  3943. try:
  3944. for line in file:
  3945. proc_line = str(line).strip('\n')
  3946. self.ui.code_editor.append(proc_line)
  3947. except Exception as e:
  3948. log.debug('App.on_view_source() -->%s' % str(e))
  3949. self.inform.emit('[ERROR]App.on_view_source() -->%s' % str(e))
  3950. return
  3951. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3952. self.handleTextChanged()
  3953. self.ui.show()
  3954. # if type(obj) == FlatCAMGerber:
  3955. # self.on_file_exportdxf()
  3956. # elif type(obj) == FlatCAMExcellon:
  3957. # self.on_file_exportexcellon()
  3958. def obj_move(self):
  3959. self.report_usage("obj_move()")
  3960. self.move_tool.run()
  3961. def on_fileopengerber(self):
  3962. """
  3963. File menu callback for opening a Gerber.
  3964. :return: None
  3965. """
  3966. self.report_usage("on_fileopengerber")
  3967. App.log.debug("on_fileopengerber()")
  3968. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3969. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3970. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3971. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3972. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3973. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3974. "Allegro Files (*.art);;" \
  3975. "Mentor Files (*.pho *.gdo);;" \
  3976. "All Files (*.*)"
  3977. try:
  3978. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3979. directory=self.get_last_folder(), filter=_filter_)
  3980. except TypeError:
  3981. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3982. filenames = [str(filename) for filename in filenames]
  3983. if len(filenames) == 0:
  3984. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  3985. else:
  3986. for filename in filenames:
  3987. if filename != '':
  3988. self.worker_task.emit({'fcn': self.open_gerber,
  3989. 'params': [filename]})
  3990. def on_fileopengerber_follow(self):
  3991. """
  3992. File menu callback for opening a Gerber.
  3993. :return: None
  3994. """
  3995. self.report_usage("on_fileopengerber_follow")
  3996. App.log.debug("on_fileopengerber_follow()")
  3997. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3998. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3999. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4000. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4001. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4002. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4003. "Allegro Files (*.art);;" \
  4004. "Mentor Files (*.pho *.gdo);;" \
  4005. "All Files (*.*)"
  4006. try:
  4007. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  4008. directory=self.get_last_folder(), filter=_filter_)
  4009. except TypeError:
  4010. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  4011. # The Qt methods above will return a QString which can cause problems later.
  4012. # So far json.dump() will fail to serialize it.
  4013. # TODO: Improve the serialization methods and remove this fix.
  4014. filename = str(filename)
  4015. follow = True
  4016. if filename == "":
  4017. self.inform.emit("[WARNING_NOTCL]Open Gerber-Follow cancelled.")
  4018. else:
  4019. self.worker_task.emit({'fcn': self.open_gerber,
  4020. 'params': [filename, follow]})
  4021. def on_fileopenexcellon(self):
  4022. """
  4023. File menu callback for opening an Excellon file.
  4024. :return: None
  4025. """
  4026. self.report_usage("on_fileopenexcellon")
  4027. App.log.debug("on_fileopenexcellon()")
  4028. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4029. "All Files (*.*)"
  4030. try:
  4031. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  4032. directory=self.get_last_folder(), filter=_filter_)
  4033. except TypeError:
  4034. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  4035. filenames = [str(filename) for filename in filenames]
  4036. if len(filenames) == 0:
  4037. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  4038. else:
  4039. for filename in filenames:
  4040. if filename != '':
  4041. self.worker_task.emit({'fcn': self.open_excellon,
  4042. 'params': [filename]})
  4043. def on_fileopengcode(self):
  4044. """
  4045. File menu call back for opening gcode.
  4046. :return: None
  4047. """
  4048. self.report_usage("on_fileopengcode")
  4049. App.log.debug("on_fileopengcode()")
  4050. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4051. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4052. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4053. "All Files (*.*)"
  4054. try:
  4055. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  4056. directory=self.get_last_folder(), filter=_filter_)
  4057. except TypeError:
  4058. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  4059. filenames = [str(filename) for filename in filenames]
  4060. if len(filenames) == 0:
  4061. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  4062. else:
  4063. for filename in filenames:
  4064. if filename != '':
  4065. self.worker_task.emit({'fcn': self.open_gcode,
  4066. 'params': [filename]})
  4067. def on_file_openproject(self):
  4068. """
  4069. File menu callback for opening a project.
  4070. :return: None
  4071. """
  4072. self.report_usage("on_file_openproject")
  4073. App.log.debug("on_file_openproject()")
  4074. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4075. try:
  4076. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  4077. directory=self.get_last_folder(), filter=_filter_)
  4078. except TypeError:
  4079. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  4080. # The Qt methods above will return a QString which can cause problems later.
  4081. # So far json.dump() will fail to serialize it.
  4082. # TODO: Improve the serialization methods and remove this fix.
  4083. filename = str(filename)
  4084. if filename == "":
  4085. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4086. else:
  4087. # self.worker_task.emit({'fcn': self.open_project,
  4088. # 'params': [filename]})
  4089. # The above was failing because open_project() is not
  4090. # thread safe. The new_project()
  4091. self.open_project(filename)
  4092. def on_file_exportsvg(self):
  4093. """
  4094. Callback for menu item File->Export SVG.
  4095. :return: None
  4096. """
  4097. self.report_usage("on_file_exportsvg")
  4098. App.log.debug("on_file_exportsvg()")
  4099. obj = self.collection.get_active()
  4100. if obj is None:
  4101. self.inform.emit("WARNING: No object selected.")
  4102. msg = "Please Select a Geometry object to export"
  4103. msgbox = QtWidgets.QMessageBox()
  4104. msgbox.setInformativeText(msg)
  4105. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4106. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4107. msgbox.exec_()
  4108. return
  4109. # Check for more compatible types and add as required
  4110. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4111. and not isinstance(obj, FlatCAMExcellon)):
  4112. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4113. msgbox = QtWidgets.QMessageBox()
  4114. msgbox.setInformativeText(msg)
  4115. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4116. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4117. msgbox.exec_()
  4118. return
  4119. name = self.collection.get_active().options["name"]
  4120. filter = "SVG File (*.svg);;All Files (*.*)"
  4121. try:
  4122. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4123. caption="Export SVG",
  4124. directory=self.get_last_save_folder() + '/' + str(name),
  4125. filter=filter)
  4126. except TypeError:
  4127. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4128. filename = str(filename)
  4129. if filename == "":
  4130. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4131. return
  4132. else:
  4133. self.export_svg(name, filename)
  4134. self.file_saved.emit("SVG", filename)
  4135. def on_file_exportpng(self):
  4136. self.report_usage("on_file_exportpng")
  4137. App.log.debug("on_file_exportpng()")
  4138. image = _screenshot()
  4139. data = np.asarray(image)
  4140. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4141. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4142. return
  4143. filter_ = "PNG File (*.png);;All Files (*.*)"
  4144. try:
  4145. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4146. caption="Export PNG Image",
  4147. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4148. filter=filter_)
  4149. except TypeError:
  4150. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4151. filename = str(filename)
  4152. if filename == "":
  4153. self.inform.emit("Export PNG cancelled.")
  4154. return
  4155. else:
  4156. write_png(filename, data)
  4157. self.file_saved.emit("png", filename)
  4158. def on_file_exportgerber(self):
  4159. """
  4160. Callback for menu item File->Export SVG.
  4161. :return: None
  4162. """
  4163. self.report_usage("on_file_exportgerber")
  4164. App.log.debug("on_file_exportgerber()")
  4165. obj = self.collection.get_active()
  4166. if obj is None:
  4167. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export.")
  4168. return
  4169. # Check for more compatible types and add as required
  4170. if not isinstance(obj, FlatCAMGerber):
  4171. self.inform.emit("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files...")
  4172. return
  4173. name = self.collection.get_active().options["name"]
  4174. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4175. try:
  4176. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4177. caption="Export Gerber",
  4178. directory=self.get_last_save_folder() + '/' + name,
  4179. filter=filter)
  4180. except TypeError:
  4181. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Gerber", filter=filter)
  4182. filename = str(filename)
  4183. if filename == "":
  4184. self.inform.emit("[WARNING_NOTCL]Export Gerber cancelled.")
  4185. return
  4186. else:
  4187. self.export_gerber(name, filename)
  4188. self.file_saved.emit("Gerber", filename)
  4189. def on_file_exportexcellon(self):
  4190. """
  4191. Callback for menu item File->Export SVG.
  4192. :return: None
  4193. """
  4194. self.report_usage("on_file_exportexcellon")
  4195. App.log.debug("on_file_exportexcellon()")
  4196. obj = self.collection.get_active()
  4197. if obj is None:
  4198. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export.")
  4199. return
  4200. # Check for more compatible types and add as required
  4201. if not isinstance(obj, FlatCAMExcellon):
  4202. self.inform.emit("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files...")
  4203. return
  4204. name = self.collection.get_active().options["name"]
  4205. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4206. try:
  4207. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4208. caption="Export Excellon",
  4209. directory=self.get_last_save_folder() + '/' + name,
  4210. filter=filter)
  4211. except TypeError:
  4212. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4213. filename = str(filename)
  4214. if filename == "":
  4215. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4216. return
  4217. else:
  4218. self.export_excellon(name, filename)
  4219. self.file_saved.emit("Excellon", filename)
  4220. def on_file_exportdxf(self):
  4221. """
  4222. Callback for menu item File->Export DXF.
  4223. :return: None
  4224. """
  4225. self.report_usage("on_file_exportdxf")
  4226. App.log.debug("on_file_exportdxf()")
  4227. obj = self.collection.get_active()
  4228. if obj is None:
  4229. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4230. msg = "Please Select a Geometry object to export"
  4231. msgbox = QtWidgets.QMessageBox()
  4232. msgbox.setInformativeText(msg)
  4233. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4234. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4235. msgbox.exec_()
  4236. return
  4237. # Check for more compatible types and add as required
  4238. if not isinstance(obj, FlatCAMGeometry):
  4239. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4240. msgbox = QtWidgets.QMessageBox()
  4241. msgbox.setInformativeText(msg)
  4242. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4243. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4244. msgbox.exec_()
  4245. return
  4246. name = self.collection.get_active().options["name"]
  4247. filter = "DXF File (*.DXF);;All Files (*.*)"
  4248. try:
  4249. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4250. caption="Export DXF",
  4251. directory=self.get_last_save_folder() + '/' + name,
  4252. filter=filter)
  4253. except TypeError:
  4254. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4255. filename = str(filename)
  4256. if filename == "":
  4257. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4258. return
  4259. else:
  4260. self.export_dxf(name, filename)
  4261. self.file_saved.emit("DXF", filename)
  4262. def on_file_importsvg(self, type_of_obj):
  4263. """
  4264. Callback for menu item File->Import SVG.
  4265. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4266. :type type_of_obj: str
  4267. :return: None
  4268. """
  4269. self.report_usage("on_file_importsvg")
  4270. App.log.debug("on_file_importsvg()")
  4271. filter = "SVG File (*.svg);;All Files (*.*)"
  4272. try:
  4273. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4274. directory=self.get_last_folder(), filter=filter)
  4275. except TypeError:
  4276. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4277. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4278. type_of_obj = "geometry"
  4279. filenames = [str(filename) for filename in filenames]
  4280. if len(filenames) == 0:
  4281. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4282. else:
  4283. for filename in filenames:
  4284. if filename != '':
  4285. self.worker_task.emit({'fcn': self.import_svg,
  4286. 'params': [filename, type_of_obj]})
  4287. def on_file_importdxf(self, type_of_obj):
  4288. """
  4289. Callback for menu item File->Import DXF.
  4290. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4291. :type type_of_obj: str
  4292. :return: None
  4293. """
  4294. self.report_usage("on_file_importdxf")
  4295. App.log.debug("on_file_importdxf()")
  4296. filter = "DXF File (*.DXF);;All Files (*.*)"
  4297. try:
  4298. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4299. directory=self.get_last_folder(), filter=filter)
  4300. except TypeError:
  4301. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4302. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4303. type_of_obj = "geometry"
  4304. filenames = [str(filename) for filename in filenames]
  4305. if len(filenames) == 0:
  4306. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4307. else:
  4308. for filename in filenames:
  4309. if filename != '':
  4310. self.worker_task.emit({'fcn': self.import_dxf,
  4311. 'params': [filename, type_of_obj]})
  4312. def on_filerunscript(self):
  4313. """
  4314. File menu callback for loading and running a TCL script.
  4315. :return: None
  4316. """
  4317. self.report_usage("on_filerunscript")
  4318. App.log.debug("on_file_runscript()")
  4319. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4320. try:
  4321. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4322. directory=self.get_last_folder(), filter=_filter_)
  4323. except TypeError:
  4324. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4325. # The Qt methods above will return a QString which can cause problems later.
  4326. # So far json.dump() will fail to serialize it.
  4327. # TODO: Improve the serialization methods and remove this fix.
  4328. filename = str(filename)
  4329. if filename == "":
  4330. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4331. else:
  4332. try:
  4333. with open(filename, "r") as tcl_script:
  4334. cmd_line_shellfile_content = tcl_script.read()
  4335. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4336. except Exception as ext:
  4337. print("ERROR: ", ext)
  4338. sys.exit(2)
  4339. def on_file_saveproject(self):
  4340. """
  4341. Callback for menu item File->Save Project. Saves the project to
  4342. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4343. if set to None. The project is saved by calling ``self.save_project()``.
  4344. :return: None
  4345. """
  4346. self.report_usage("on_file_saveproject")
  4347. if self.project_filename is None:
  4348. self.on_file_saveprojectas()
  4349. else:
  4350. self.worker_task.emit({'fcn': self.save_project,
  4351. 'params': [self.project_filename]})
  4352. # self.save_project(self.project_filename)
  4353. self.file_opened.emit("project", self.project_filename)
  4354. self.file_saved.emit("project", self.project_filename)
  4355. self.should_we_save = False
  4356. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4357. """
  4358. Callback for menu item File->Save Project As... Opens a file
  4359. chooser and saves the project to the given file via
  4360. ``self.save_project()``.
  4361. :return: None
  4362. """
  4363. self.report_usage("on_file_saveprojectas")
  4364. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4365. try:
  4366. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4367. caption="Save Project As ...",
  4368. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4369. filter=filter_)
  4370. except TypeError:
  4371. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4372. filename = str(filename)
  4373. if filename == '':
  4374. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4375. return
  4376. try:
  4377. f = open(filename, 'r')
  4378. f.close()
  4379. exists = True
  4380. except IOError:
  4381. exists = False
  4382. # msg = "Project file exists. Overwrite?"
  4383. # if exists:
  4384. # msgbox = QtWidgets.QMessageBox()
  4385. # msgbox.setInformativeText(msg)
  4386. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4387. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4388. # result = msgbox.exec_()
  4389. # if result ==QtWidgets.QMessageBox.Cancel:
  4390. # return
  4391. if thread is True:
  4392. self.worker_task.emit({'fcn': self.save_project,
  4393. 'params': [filename]})
  4394. else:
  4395. self.save_project(filename)
  4396. # self.save_project(filename)
  4397. self.file_opened.emit("project", filename)
  4398. self.file_saved.emit("project", filename)
  4399. if not make_copy:
  4400. self.project_filename = filename
  4401. self.should_we_save = False
  4402. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4403. """
  4404. Exports a Geometry Object to an SVG file.
  4405. :param filename: Path to the SVG file to save to.
  4406. :return:
  4407. """
  4408. self.report_usage("export_svg()")
  4409. if filename is None:
  4410. filename = self.defaults["global_last_save_folder"]
  4411. self.log.debug("export_svg()")
  4412. try:
  4413. obj = self.collection.get_by_name(str(obj_name))
  4414. except:
  4415. # TODO: The return behavior has not been established... should raise exception?
  4416. return "Could not retrieve object: %s" % obj_name
  4417. with self.proc_container.new("Exporting SVG") as proc:
  4418. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4419. # Determine bounding area for svg export
  4420. bounds = obj.bounds()
  4421. size = obj.size()
  4422. # Convert everything to strings for use in the xml doc
  4423. svgwidth = str(size[0])
  4424. svgheight = str(size[1])
  4425. minx = str(bounds[0])
  4426. miny = str(bounds[1] - size[1])
  4427. uom = obj.units.lower()
  4428. # Add a SVG Header and footer to the svg output from shapely
  4429. # The transform flips the Y Axis so that everything renders
  4430. # properly within svg apps such as inkscape
  4431. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4432. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4433. svg_header += 'width="' + svgwidth + uom + '" '
  4434. svg_header += 'height="' + svgheight + uom + '" '
  4435. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4436. svg_header += '<g transform="scale(1,-1)">'
  4437. svg_footer = '</g> </svg>'
  4438. svg_elem = svg_header + exported_svg + svg_footer
  4439. # Parse the xml through a xml parser just to add line feeds
  4440. # and to make it look more pretty for the output
  4441. svgcode = parse_xml_string(svg_elem)
  4442. with open(filename, 'w') as fp:
  4443. fp.write(svgcode.toprettyxml())
  4444. self.file_saved.emit("SVG", filename)
  4445. self.inform.emit("[success] SVG file exported to " + filename)
  4446. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4447. """
  4448. Exports a Geometry Object to an SVG file in negative.
  4449. :param filename: Path to the SVG file to save to.
  4450. :param: use_thread: If True use threads
  4451. :type: Bool
  4452. :return:
  4453. """
  4454. self.report_usage("export_negative()")
  4455. if filename is None:
  4456. filename = self.defaults["global_last_save_folder"]
  4457. self.log.debug("export_svg() negative")
  4458. try:
  4459. obj = self.collection.get_by_name(str(obj_name))
  4460. except:
  4461. # TODO: The return behavior has not been established... should raise exception?
  4462. return "Could not retrieve object: %s" % obj_name
  4463. try:
  4464. box = self.collection.get_by_name(str(box_name))
  4465. except:
  4466. # TODO: The return behavior has not been established... should raise exception?
  4467. return "Could not retrieve object: %s" % box_name
  4468. if box is None:
  4469. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4470. box = obj
  4471. def make_negative_film():
  4472. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4473. self.progress.emit(40)
  4474. # Determine bounding area for svg export
  4475. bounds = box.bounds()
  4476. size = box.size()
  4477. uom = obj.units.lower()
  4478. # Convert everything to strings for use in the xml doc
  4479. svgwidth = str(size[0] + (2 * boundary))
  4480. svgheight = str(size[1] + (2 * boundary))
  4481. minx = str(bounds[0] - boundary)
  4482. miny = str(bounds[1] + boundary + size[1])
  4483. miny_rect = str(bounds[1] - boundary)
  4484. # Add a SVG Header and footer to the svg output from shapely
  4485. # The transform flips the Y Axis so that everything renders
  4486. # properly within svg apps such as inkscape
  4487. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4488. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4489. svg_header += 'width="' + svgwidth + uom + '" '
  4490. svg_header += 'height="' + svgheight + uom + '" '
  4491. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4492. svg_header += '>'
  4493. svg_header += '<g transform="scale(1,-1)">'
  4494. svg_footer = '</g> </svg>'
  4495. self.progress.emit(60)
  4496. # Change the attributes of the exported SVG
  4497. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4498. # We set opacity to maximum
  4499. # We set the color to WHITE
  4500. root = ET.fromstring(exported_svg)
  4501. for child in root:
  4502. child.set('fill', '#FFFFFF')
  4503. child.set('opacity', '1.0')
  4504. child.set('stroke', '#FFFFFF')
  4505. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4506. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4507. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4508. first_svg_elem_tag = 'rect'
  4509. first_svg_elem_attribs = {
  4510. 'x': minx,
  4511. 'y': miny_rect,
  4512. 'width': svgwidth,
  4513. 'height': svgheight,
  4514. 'id': 'neg_rect',
  4515. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4516. }
  4517. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4518. exported_svg = ET.tostring(root)
  4519. svg_elem = svg_header + str(exported_svg) + svg_footer
  4520. self.progress.emit(80)
  4521. # Parse the xml through a xml parser just to add line feeds
  4522. # and to make it look more pretty for the output
  4523. doc = parse_xml_string(svg_elem)
  4524. with open(filename, 'w') as fp:
  4525. fp.write(doc.toprettyxml())
  4526. self.progress.emit(100)
  4527. self.file_saved.emit("SVG", filename)
  4528. self.inform.emit("[success] SVG file exported to " + filename)
  4529. if use_thread is True:
  4530. proc = self.proc_container.new("Generating Film ... Please wait.")
  4531. def job_thread_film(app_obj):
  4532. try:
  4533. make_negative_film()
  4534. except Exception as e:
  4535. proc.done()
  4536. return
  4537. proc.done()
  4538. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4539. else:
  4540. make_negative_film()
  4541. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4542. """
  4543. Exports a Geometry Object to an SVG file in negative.
  4544. :param filename: Path to the SVG file to save to.
  4545. :param: use_thread: If True use threads
  4546. :type: Bool
  4547. :return:
  4548. """
  4549. self.report_usage("export_svg_black()")
  4550. if filename is None:
  4551. filename = self.defaults["global_last_save_folder"]
  4552. self.log.debug("export_svg() black")
  4553. try:
  4554. obj = self.collection.get_by_name(str(obj_name))
  4555. except:
  4556. # TODO: The return behavior has not been established... should raise exception?
  4557. return "Could not retrieve object: %s" % obj_name
  4558. try:
  4559. box = self.collection.get_by_name(str(box_name))
  4560. except:
  4561. # TODO: The return behavior has not been established... should raise exception?
  4562. return "Could not retrieve object: %s" % box_name
  4563. if box is None:
  4564. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4565. box = obj
  4566. def make_black_film():
  4567. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4568. self.progress.emit(40)
  4569. # Change the attributes of the exported SVG
  4570. # We don't need stroke-width
  4571. # We set opacity to maximum
  4572. # We set the colour to WHITE
  4573. root = ET.fromstring(exported_svg)
  4574. for child in root:
  4575. child.set('fill', '#000000')
  4576. child.set('opacity', '1.0')
  4577. child.set('stroke', '#000000')
  4578. exported_svg = ET.tostring(root)
  4579. # Determine bounding area for svg export
  4580. bounds = box.bounds()
  4581. size = box.size()
  4582. # This contain the measure units
  4583. uom = obj.units.lower()
  4584. # Define a boundary around SVG of about 1.0mm (~39mils)
  4585. if uom in "mm":
  4586. boundary = 1.0
  4587. else:
  4588. boundary = 0.0393701
  4589. self.progress.emit(80)
  4590. # Convert everything to strings for use in the xml doc
  4591. svgwidth = str(size[0] + (2 * boundary))
  4592. svgheight = str(size[1] + (2 * boundary))
  4593. minx = str(bounds[0] - boundary)
  4594. miny = str(bounds[1] + boundary + size[1])
  4595. self.log.debug(minx)
  4596. self.log.debug(miny)
  4597. # Add a SVG Header and footer to the svg output from shapely
  4598. # The transform flips the Y Axis so that everything renders
  4599. # properly within svg apps such as inkscape
  4600. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4601. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4602. svg_header += 'width="' + svgwidth + uom + '" '
  4603. svg_header += 'height="' + svgheight + uom + '" '
  4604. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4605. svg_header += '>'
  4606. svg_header += '<g transform="scale(1,-1)">'
  4607. svg_footer = '</g> </svg>'
  4608. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4609. self.progress.emit(90)
  4610. # Parse the xml through a xml parser just to add line feeds
  4611. # and to make it look more pretty for the output
  4612. doc = parse_xml_string(svg_elem)
  4613. with open(filename, 'w') as fp:
  4614. fp.write(doc.toprettyxml())
  4615. self.progress.emit(100)
  4616. self.file_saved.emit("SVG", filename)
  4617. self.inform.emit("[success] SVG file exported to " + filename)
  4618. if use_thread is True:
  4619. proc = self.proc_container.new("Generating Film ... Please wait.")
  4620. def job_thread_film(app_obj):
  4621. try:
  4622. make_black_film()
  4623. except Exception as e:
  4624. proc.done()
  4625. return
  4626. proc.done()
  4627. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4628. else:
  4629. make_black_film()
  4630. def export_gerber(self, obj_name, filename, use_thread=True):
  4631. """
  4632. Exports a Gerber Object to an Gerber file.
  4633. :param filename: Path to the Gerber file to save to.
  4634. :return:
  4635. """
  4636. self.report_usage("export_gerber()")
  4637. if filename is None:
  4638. filename = self.defaults["global_last_save_folder"]
  4639. self.log.debug("export_gerber()")
  4640. obj = self.collection.get_by_name(obj_name)
  4641. file_string = StringIO(obj.source_file)
  4642. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4643. with open(filename, 'w') as file:
  4644. file.writelines('G04*\n')
  4645. file.writelines('G04 GERBER (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  4646. (str(self.version), str(self.version_date)))
  4647. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  4648. file.writelines('G04 Created on : %s*\n' % time_string)
  4649. for line in file_string:
  4650. file.writelines(line)
  4651. def export_excellon(self, obj_name, filename, use_thread=True):
  4652. """
  4653. Exports a Excellon Object to an Excellon file.
  4654. :param filename: Path to the Excellon file to save to.
  4655. :return:
  4656. """
  4657. self.report_usage("export_excellon()")
  4658. if filename is None:
  4659. filename = self.defaults["global_last_save_folder"]
  4660. self.log.debug("export_excellon()")
  4661. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  4662. self.defaults["excellon_exp_decimals"]
  4663. )
  4664. units = ''
  4665. try:
  4666. obj = self.collection.get_by_name(str(obj_name))
  4667. except:
  4668. # TODO: The return behavior has not been established... should raise exception?
  4669. return "Could not retrieve object: %s" % obj_name
  4670. # updated units
  4671. eunits = self.defaults["excellon_exp_units"]
  4672. ewhole = self.defaults["excellon_exp_integer"]
  4673. efract = self.defaults["excellon_exp_decimals"]
  4674. ezeros = self.defaults["excellon_exp_zeros"]
  4675. eformat = self.defaults[ "excellon_exp_format"]
  4676. fc_units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4677. if fc_units == 'MM':
  4678. factor = 1 if eunits == 'METRIC' else 0.03937
  4679. else:
  4680. factor = 25.4 if eunits == 'METRIC' else 1
  4681. def make_excellon():
  4682. try:
  4683. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4684. header = 'M48\n'
  4685. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4686. (str(self.version), str(self.version_date))
  4687. header += ';Filename: %s' % str(obj_name) + '\n'
  4688. header += ';Created on : %s' % time_str + '\n'
  4689. if eformat == 'dec':
  4690. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  4691. header += eunits + '\n'
  4692. for tool in obj.tools:
  4693. if eunits == 'METRIC':
  4694. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4695. tool=str(tool),
  4696. dec=2)
  4697. else:
  4698. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4699. tool=str(tool),
  4700. dec=4)
  4701. else:
  4702. if ezeros == 'LZ':
  4703. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4704. form='ndec', e_zeros='LZ', factor=factor)
  4705. header += '%s,%s\n' % (eunits, 'LZ')
  4706. header += format_exc
  4707. for tool in obj.tools:
  4708. if eunits == 'METRIC':
  4709. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4710. tool=str(tool),
  4711. dec=2)
  4712. else:
  4713. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4714. tool=str(tool),
  4715. dec=4)
  4716. else:
  4717. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4718. form='ndec', e_zeros='TZ', factor=factor)
  4719. header += '%s,%s\n' % (eunits, 'TZ')
  4720. header += format_exc
  4721. for tool in obj.tools:
  4722. if eunits == 'METRIC':
  4723. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4724. tool=str(tool),
  4725. dec=2)
  4726. else:
  4727. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4728. tool=str(tool),
  4729. dec=4)
  4730. header += '%\n'
  4731. footer = 'M30\n'
  4732. exported_excellon = header
  4733. exported_excellon += excellon_code
  4734. exported_excellon += footer
  4735. with open(filename, 'w') as fp:
  4736. fp.write(exported_excellon)
  4737. self.file_saved.emit("Excellon", filename)
  4738. self.inform.emit("[success] Excellon file exported to " + filename)
  4739. except Exception as e:
  4740. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  4741. return 'fail'
  4742. if use_thread is True:
  4743. with self.proc_container.new("Exporting Excellon") as proc:
  4744. def job_thread_exc(app_obj):
  4745. ret = make_excellon()
  4746. if ret == 'fail':
  4747. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4748. return
  4749. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4750. else:
  4751. ret = make_excellon()
  4752. if ret == 'fail':
  4753. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4754. return
  4755. def export_dxf(self, obj_name, filename, use_thread=True):
  4756. """
  4757. Exports a Geometry Object to an DXF file.
  4758. :param filename: Path to the DXF file to save to.
  4759. :return:
  4760. """
  4761. self.report_usage("export_dxf()")
  4762. if filename is None:
  4763. filename = self.defaults["global_last_save_folder"]
  4764. self.log.debug("export_dxf()")
  4765. format_exc = ''
  4766. units = ''
  4767. try:
  4768. obj = self.collection.get_by_name(str(obj_name))
  4769. except:
  4770. # TODO: The return behavior has not been established... should raise exception?
  4771. return "Could not retrieve object: %s" % obj_name
  4772. # updated units
  4773. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4774. if units == 'IN' or units == 'INCH':
  4775. units = 'INCH'
  4776. elif units == 'MM' or units == 'METIRC':
  4777. units ='METRIC'
  4778. def make_dxf():
  4779. try:
  4780. dxf_code = obj.export_dxf()
  4781. dxf_code.saveas(filename)
  4782. self.file_saved.emit("DXF", filename)
  4783. self.inform.emit("[success] DXF file exported to " + filename)
  4784. except:
  4785. return 'fail'
  4786. if use_thread is True:
  4787. with self.proc_container.new("Exporting DXF") as proc:
  4788. def job_thread_exc(app_obj):
  4789. ret = make_dxf()
  4790. if ret == 'fail':
  4791. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4792. return
  4793. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4794. else:
  4795. ret = make_dxf()
  4796. if ret == 'fail':
  4797. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4798. return
  4799. def import_svg(self, filename, geo_type='geometry', outname=None):
  4800. """
  4801. Adds a new Geometry Object to the projects and populates
  4802. it with shapes extracted from the SVG file.
  4803. :param filename: Path to the SVG file.
  4804. :param outname:
  4805. :return:
  4806. """
  4807. self.report_usage("import_svg()")
  4808. obj_type = ""
  4809. if geo_type is None or geo_type == "geometry":
  4810. obj_type = "geometry"
  4811. elif geo_type == "gerber":
  4812. obj_type = geo_type
  4813. else:
  4814. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4815. "Only Geometry and Gerber are supported")
  4816. return
  4817. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4818. def obj_init(geo_obj, app_obj):
  4819. geo_obj.import_svg(filename, obj_type, units=units)
  4820. geo_obj.multigeo = False
  4821. with self.proc_container.new("Importing SVG") as proc:
  4822. # Object name
  4823. name = outname or filename.split('/')[-1].split('\\')[-1]
  4824. self.new_object(obj_type, name, obj_init, autoselected=False)
  4825. self.progress.emit(20)
  4826. # Register recent file
  4827. self.file_opened.emit("svg", filename)
  4828. # GUI feedback
  4829. self.inform.emit("[success] Opened: " + filename)
  4830. self.progress.emit(100)
  4831. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4832. """
  4833. Adds a new Geometry Object to the projects and populates
  4834. it with shapes extracted from the DXF file.
  4835. :param filename: Path to the DXF file.
  4836. :param outname:
  4837. :type putname: str
  4838. :return:
  4839. """
  4840. self.report_usage("import_dxf()")
  4841. obj_type = ""
  4842. if geo_type is None or geo_type == "geometry":
  4843. obj_type = "geometry"
  4844. elif geo_type == "gerber":
  4845. obj_type = geo_type
  4846. else:
  4847. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4848. "Only Geometry and Gerber are supported")
  4849. return
  4850. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4851. def obj_init(geo_obj, app_obj):
  4852. geo_obj.import_dxf(filename, obj_type, units=units)
  4853. geo_obj.multigeo = False
  4854. with self.proc_container.new("Importing DXF") as proc:
  4855. # Object name
  4856. name = outname or filename.split('/')[-1].split('\\')[-1]
  4857. self.new_object(obj_type, name, obj_init, autoselected=False)
  4858. self.progress.emit(20)
  4859. # Register recent file
  4860. self.file_opened.emit("dxf", filename)
  4861. # GUI feedback
  4862. self.inform.emit("[success] Opened: " + filename)
  4863. self.progress.emit(100)
  4864. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4865. """
  4866. Adds a new Geometry Object to the projects and populates
  4867. it with shapes extracted from the SVG file.
  4868. :param filename: Path to the SVG file.
  4869. :param outname:
  4870. :return:
  4871. """
  4872. self.report_usage("import_image()")
  4873. obj_type = ""
  4874. if type is None or type == "geometry":
  4875. obj_type = "geometry"
  4876. elif type == "gerber":
  4877. obj_type = type
  4878. else:
  4879. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4880. "Only Geometry and Gerber are supported")
  4881. return
  4882. def obj_init(geo_obj, app_obj):
  4883. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4884. geo_obj.multigeo = False
  4885. with self.proc_container.new("Importing Image") as proc:
  4886. # Object name
  4887. name = outname or filename.split('/')[-1].split('\\')[-1]
  4888. units = self.general_options_form.general_app_group.units_radio.get_value()
  4889. self.new_object(obj_type, name, obj_init)
  4890. self.progress.emit(20)
  4891. # Register recent file
  4892. self.file_opened.emit("image", filename)
  4893. # GUI feedback
  4894. self.inform.emit("[success] Opened: " + filename)
  4895. self.progress.emit(100)
  4896. def open_gerber(self, filename, follow=False, outname=None):
  4897. """
  4898. Opens a Gerber file, parses it and creates a new object for
  4899. it in the program. Thread-safe.
  4900. :param outname: Name of the resulting object. None causes the
  4901. name to be that of the file.
  4902. :param filename: Gerber file filename
  4903. :type filename: str
  4904. :param follow: If true, the parser will not create polygons, just lines
  4905. following the gerber path.
  4906. :type follow: bool
  4907. :return: None
  4908. """
  4909. # How the object should be initialized
  4910. def obj_init(gerber_obj, app_obj):
  4911. assert isinstance(gerber_obj, FlatCAMGerber), \
  4912. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4913. # Opening the file happens here
  4914. self.progress.emit(30)
  4915. try:
  4916. gerber_obj.parse_file(filename, follow=follow)
  4917. except IOError:
  4918. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4919. app_obj.progress.emit(0)
  4920. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4921. return "fail"
  4922. except ParseError as err:
  4923. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4924. app_obj.progress.emit(0)
  4925. self.log.error(str(err))
  4926. return "fail"
  4927. except:
  4928. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4929. msg += traceback.format_exc()
  4930. app_obj.inform.emit(msg)
  4931. return "fail"
  4932. if gerber_obj.is_empty():
  4933. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4934. # self.collection.set_active(gerber_obj.options["name"])
  4935. # self.collection.delete_active()
  4936. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4937. return "fail"
  4938. # Further parsing
  4939. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4940. if follow is False:
  4941. App.log.debug("open_gerber()")
  4942. else:
  4943. App.log.debug("open_gerber() with 'follow' attribute")
  4944. with self.proc_container.new("Opening Gerber") as proc:
  4945. self.progress.emit(10)
  4946. # Object name
  4947. name = outname or filename.split('/')[-1].split('\\')[-1]
  4948. ### Object creation ###
  4949. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4950. if ret == 'fail':
  4951. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4952. return
  4953. # Register recent file
  4954. self.file_opened.emit("gerber", filename)
  4955. self.progress.emit(100)
  4956. # GUI feedback
  4957. self.inform.emit("[success] Opened: " + filename)
  4958. def open_excellon(self, filename, outname=None):
  4959. """
  4960. Opens an Excellon file, parses it and creates a new object for
  4961. it in the program. Thread-safe.
  4962. :param outname: Name of the resulting object. None causes the
  4963. name to be that of the file.
  4964. :param filename: Excellon file filename
  4965. :type filename: str
  4966. :return: None
  4967. """
  4968. App.log.debug("open_excellon()")
  4969. #self.progress.emit(10)
  4970. # How the object should be initialized
  4971. def obj_init(excellon_obj, app_obj):
  4972. # self.progress.emit(20)
  4973. try:
  4974. ret = excellon_obj.parse_file(filename)
  4975. if ret == "fail":
  4976. log.debug("Excellon parsing failed.")
  4977. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4978. return "fail"
  4979. except IOError:
  4980. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  4981. log.debug("Could not open Excellon object.")
  4982. self.progress.emit(0) # TODO: self and app_bjj mixed
  4983. return "fail"
  4984. except:
  4985. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  4986. msg += traceback.format_exc()
  4987. app_obj.inform.emit(msg)
  4988. return "fail"
  4989. ret = excellon_obj.create_geometry()
  4990. if ret == 'fail':
  4991. log.debug("Could not create geometry for Excellon object.")
  4992. return "fail"
  4993. # if excellon_obj.is_empty():
  4994. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4995. # return "fail"
  4996. for tool in excellon_obj.tools:
  4997. if excellon_obj.tools[tool]['solid_geometry']:
  4998. return
  4999. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5000. return "fail"
  5001. with self.proc_container.new("Opening Excellon."):
  5002. # Object name
  5003. name = outname or filename.split('/')[-1].split('\\')[-1]
  5004. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5005. if ret == 'fail':
  5006. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  5007. return
  5008. # Register recent file
  5009. self.file_opened.emit("excellon", filename)
  5010. # GUI feedback
  5011. self.inform.emit("[success] Opened: " + filename)
  5012. # self.progress.emit(100)
  5013. def open_gcode(self, filename, outname=None):
  5014. """
  5015. Opens a G-gcode file, parses it and creates a new object for
  5016. it in the program. Thread-safe.
  5017. :param outname: Name of the resulting object. None causes the
  5018. name to be that of the file.
  5019. :param filename: G-code file filename
  5020. :type filename: str
  5021. :return: None
  5022. """
  5023. App.log.debug("open_gcode()")
  5024. # How the object should be initialized
  5025. def obj_init(job_obj, app_obj_):
  5026. """
  5027. :type app_obj_: App
  5028. """
  5029. assert isinstance(app_obj_, App), \
  5030. "Initializer expected App, got %s" % type(app_obj_)
  5031. self.progress.emit(10)
  5032. try:
  5033. f = open(filename)
  5034. gcode = f.read()
  5035. f.close()
  5036. except IOError:
  5037. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  5038. self.progress.emit(0)
  5039. return "fail"
  5040. job_obj.gcode = gcode
  5041. self.progress.emit(20)
  5042. ret = job_obj.gcode_parse()
  5043. if ret == "fail":
  5044. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  5045. return "fail"
  5046. self.progress.emit(60)
  5047. job_obj.create_geometry()
  5048. with self.proc_container.new("Opening G-Code."):
  5049. # Object name
  5050. name = outname or filename.split('/')[-1].split('\\')[-1]
  5051. # New object creation and file processing
  5052. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5053. if ret == 'fail':
  5054. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5055. "Attempting to create a FlatCAM CNCJob Object from "
  5056. "G-Code file failed during processing")
  5057. return "fail"
  5058. # Register recent file
  5059. self.file_opened.emit("cncjob", filename)
  5060. # GUI feedback
  5061. self.inform.emit("[success] Opened: " + filename)
  5062. self.progress.emit(100)
  5063. def open_project(self, filename, run_from_arg=None):
  5064. """
  5065. Loads a project from the specified file.
  5066. 1) Loads and parses file
  5067. 2) Registers the file as recently opened.
  5068. 3) Calls on_file_new()
  5069. 4) Updates options
  5070. 5) Calls new_object() with the object's from_dict() as init method.
  5071. 6) Calls plot_all()
  5072. :param filename: Name of the file from which to load.
  5073. :type filename: str
  5074. :return: None
  5075. """
  5076. App.log.debug("Opening project: " + filename)
  5077. # Open and parse
  5078. try:
  5079. f = open(filename, 'r')
  5080. except IOError:
  5081. App.log.error("Failed to open project file: %s" % filename)
  5082. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5083. return
  5084. try:
  5085. d = json.load(f, object_hook=dict2obj)
  5086. except:
  5087. App.log.error("Failed to parse project file: %s" % filename)
  5088. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  5089. f.close()
  5090. return
  5091. self.file_opened.emit("project", filename)
  5092. # Clear the current project
  5093. ## NOT THREAD SAFE ##
  5094. if run_from_arg is True:
  5095. pass
  5096. else:
  5097. self.on_file_new()
  5098. #Project options
  5099. self.options.update(d['options'])
  5100. self.project_filename = filename
  5101. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5102. self.set_screen_units(self.options["units"])
  5103. # Re create objects
  5104. App.log.debug("Re-creating objects...")
  5105. for obj in d['objs']:
  5106. def obj_init(obj_inst, app_inst):
  5107. obj_inst.from_dict(obj)
  5108. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5109. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5110. self.plot_all()
  5111. self.inform.emit("[success] Project loaded from: " + filename)
  5112. self.should_we_save = False
  5113. App.log.debug("Project loaded")
  5114. def propagate_defaults(self, silent=False):
  5115. """
  5116. This method is used to set default values in classes. It's
  5117. an alternative to project options but allows the use
  5118. of values invisible to the user.
  5119. :return: None
  5120. """
  5121. if silent is False:
  5122. self.log.debug("propagate_defaults()")
  5123. # Which objects to update the given parameters.
  5124. routes = {
  5125. "global_zdownrate": CNCjob,
  5126. "excellon_zeros": Excellon,
  5127. "excellon_format_upper_in": Excellon,
  5128. "excellon_format_lower_in": Excellon,
  5129. "excellon_format_upper_mm": Excellon,
  5130. "excellon_format_lower_mm": Excellon,
  5131. "excellon_units": Excellon,
  5132. "gerber_use_buffer_for_union": Gerber,
  5133. "geometry_multidepth": Geometry
  5134. }
  5135. for param in routes:
  5136. if param in routes[param].defaults:
  5137. try:
  5138. routes[param].defaults[param] = self.defaults[param]
  5139. if silent is False:
  5140. self.log.debug(" " + param + " OK")
  5141. except KeyError:
  5142. if silent is False:
  5143. self.log.debug(" ERROR: " + param + " not in defaults.")
  5144. else:
  5145. # Try extracting the name:
  5146. # classname_param here is param in the object
  5147. if param.find(routes[param].__name__.lower() + "_") == 0:
  5148. p = param[len(routes[param].__name__) + 1:]
  5149. if p in routes[param].defaults:
  5150. routes[param].defaults[p] = self.defaults[param]
  5151. if silent is False:
  5152. self.log.debug(" " + param + " OK!")
  5153. def restore_main_win_geom(self):
  5154. try:
  5155. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5156. self.defaults["global_def_win_y"],
  5157. self.defaults["global_def_win_w"],
  5158. self.defaults["global_def_win_h"])
  5159. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5160. settings = QSettings("Open Source", "FlatCAM")
  5161. if settings.contains("maximized_gui"):
  5162. maximized_ui = settings.value('maximized_gui', type=bool)
  5163. if maximized_ui is True:
  5164. self.ui.showMaximized()
  5165. except KeyError:
  5166. pass
  5167. def plot_all(self, zoom=True):
  5168. """
  5169. Re-generates all plots from all objects.
  5170. :return: None
  5171. """
  5172. self.log.debug("Plot_all()")
  5173. for obj in self.collection.get_list():
  5174. def worker_task(obj):
  5175. with self.proc_container.new("Plotting"):
  5176. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5177. if zoom:
  5178. self.object_plotted.emit(obj)
  5179. # Send to worker
  5180. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5181. # self.progress.emit(10)
  5182. #
  5183. # def worker_task(app_obj):
  5184. # print "worker task"
  5185. # percentage = 0.1
  5186. # try:
  5187. # delta = 0.9 / len(self.collection.get_list())
  5188. # except ZeroDivisionError:
  5189. # self.progress.emit(0)
  5190. # return
  5191. # for obj in self.collection.get_list():
  5192. # with self.proc_container.new("Plotting"):
  5193. # obj.plot()
  5194. # app_obj.object_plotted.emit(obj)
  5195. #
  5196. # percentage += delta
  5197. # self.progress.emit(int(percentage*100))
  5198. #
  5199. # self.progress.emit(0)
  5200. # self.plots_updated.emit()
  5201. #
  5202. # # Send to worker
  5203. # #self.worker.add_task(worker_task, [self])
  5204. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5205. def register_folder(self, filename):
  5206. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5207. def register_save_folder(self, filename):
  5208. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5209. def set_progress_bar(self, percentage, text=""):
  5210. self.ui.progress_bar.setValue(int(percentage))
  5211. def setup_shell(self):
  5212. """
  5213. Creates shell functions. Runs once at startup.
  5214. :return: None
  5215. """
  5216. self.log.debug("setup_shell()")
  5217. def shelp(p=None):
  5218. if not p:
  5219. return "Available commands:\n" + \
  5220. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5221. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5222. if p not in commands:
  5223. return "Unknown command: %s" % p
  5224. return commands[p]["help"]
  5225. # --- Migrated to new architecture ---
  5226. # def options(name):
  5227. # ops = self.collection.get_by_name(str(name)).options
  5228. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5229. def h(*args):
  5230. """
  5231. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5232. and standalone parameters into list.
  5233. """
  5234. kwa = {}
  5235. a = []
  5236. n = len(args)
  5237. name = None
  5238. for i in range(n):
  5239. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5240. if match:
  5241. assert name is None
  5242. name = match.group(1)
  5243. continue
  5244. if name is None:
  5245. a.append(args[i])
  5246. else:
  5247. kwa[name] = args[i]
  5248. name = None
  5249. return a, kwa
  5250. @contextmanager
  5251. def wait_signal(signal, timeout=10000):
  5252. """
  5253. Block loop until signal emitted, timeout (ms) elapses
  5254. or unhandled exception happens in a thread.
  5255. :param signal: Signal to wait for.
  5256. """
  5257. loop = QtCore.QEventLoop()
  5258. # Normal termination
  5259. signal.connect(loop.quit)
  5260. # Termination by exception in thread
  5261. self.thread_exception.connect(loop.quit)
  5262. status = {'timed_out': False}
  5263. def report_quit():
  5264. status['timed_out'] = True
  5265. loop.quit()
  5266. yield
  5267. # Temporarily change how exceptions are managed.
  5268. oeh = sys.excepthook
  5269. ex = []
  5270. def except_hook(type_, value, traceback_):
  5271. ex.append(value)
  5272. oeh(type_, value, traceback_)
  5273. sys.excepthook = except_hook
  5274. # Terminate on timeout
  5275. if timeout is not None:
  5276. QtCore.QTimer.singleShot(timeout, report_quit)
  5277. #### Block ####
  5278. loop.exec_()
  5279. # Restore exception management
  5280. sys.excepthook = oeh
  5281. if ex:
  5282. self.raiseTclError(str(ex[0]))
  5283. if status['timed_out']:
  5284. raise Exception('Timed out!')
  5285. def make_docs():
  5286. output = ''
  5287. import collections
  5288. od = collections.OrderedDict(sorted(commands.items()))
  5289. for cmd_, val in od.items():
  5290. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5291. t = val['help']
  5292. usage_i = t.find('>')
  5293. if usage_i < 0:
  5294. expl = t
  5295. output += expl + '\n\n'
  5296. continue
  5297. expl = t[:usage_i - 1]
  5298. output += expl + '\n\n'
  5299. end_usage_i = t[usage_i:].find('\n')
  5300. if end_usage_i < 0:
  5301. end_usage_i = len(t[usage_i:])
  5302. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5303. else:
  5304. extras = t[usage_i+end_usage_i+1:]
  5305. parts = [s.strip() for s in extras.split('\n')]
  5306. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5307. for p in parts:
  5308. output += ' ' + p + '\n\n'
  5309. return output
  5310. '''
  5311. Howto implement TCL shell commands:
  5312. All parameters passed to command should be possible to set as None and test it afterwards.
  5313. This is because we need to see error caused in tcl,
  5314. if None value as default parameter is not allowed TCL will return empty error.
  5315. Use:
  5316. def mycommand(name=None,...):
  5317. Test it like this:
  5318. if name is None:
  5319. self.raise_tcl_error('Argument name is missing.')
  5320. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5321. otherwise we will miss it and processing will silently continue.
  5322. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5323. which is catched in exec_command and displayed in TCL shell console with red background.
  5324. Error in console is displayed with TCL trace.
  5325. This behavior works only within main thread,
  5326. errors with promissed tasks can be catched and detected only with log.
  5327. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5328. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5329. '''
  5330. commands = {
  5331. 'help': {
  5332. 'fcn': shelp,
  5333. 'help': "Shows list of commands."
  5334. },
  5335. }
  5336. # Import/overwrite tcl commands as objects of TclCommand descendants
  5337. # This modifies the variable 'commands'.
  5338. tclCommands.register_all_commands(self, commands)
  5339. # Add commands to the tcl interpreter
  5340. for cmd in commands:
  5341. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5342. # Make the tcl puts function return instead of print to stdout
  5343. self.tcl.eval('''
  5344. rename puts original_puts
  5345. proc puts {args} {
  5346. if {[llength $args] == 1} {
  5347. return "[lindex $args 0]"
  5348. } else {
  5349. eval original_puts $args
  5350. }
  5351. }
  5352. ''')
  5353. def setup_recent_items(self):
  5354. # TODO: Move this to constructor
  5355. icons = {
  5356. "gerber": "share/flatcam_icon16.png",
  5357. "excellon": "share/drill16.png",
  5358. "cncjob": "share/cnc16.png",
  5359. "project": "share/project16.png",
  5360. "svg": "share/geometry16.png",
  5361. "dxf": "share/dxf16.png",
  5362. "image": "share/image16.png"
  5363. }
  5364. openers = {
  5365. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5366. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5367. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5368. 'project': self.open_project,
  5369. 'svg': self.import_svg,
  5370. 'dxf': self.import_dxf,
  5371. 'image': self.import_image
  5372. }
  5373. # Open file
  5374. try:
  5375. f = open(self.data_path + '/recent.json')
  5376. except IOError:
  5377. App.log.error("Failed to load recent item list.")
  5378. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5379. return
  5380. try:
  5381. self.recent = json.load(f)
  5382. except json.scanner.JSONDecodeError:
  5383. App.log.error("Failed to parse recent item list.")
  5384. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5385. f.close()
  5386. return
  5387. f.close()
  5388. # Closure needed to create callbacks in a loop.
  5389. # Otherwise late binding occurs.
  5390. def make_callback(func, fname):
  5391. def opener():
  5392. func(fname)
  5393. return opener
  5394. def reset_recent():
  5395. # Reset menu
  5396. self.ui.recent.clear()
  5397. self.recent = []
  5398. try:
  5399. f = open(self.data_path + '/recent.json', 'w')
  5400. except IOError:
  5401. App.log.error("Failed to open recent items file for writing.")
  5402. return
  5403. json.dump(self.recent, f)
  5404. # Reset menu
  5405. self.ui.recent.clear()
  5406. # Create menu items
  5407. for recent in self.recent:
  5408. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5409. try:
  5410. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5411. # Attach callback
  5412. o = make_callback(openers[recent["kind"]], recent['filename'])
  5413. action.triggered.connect(o)
  5414. self.ui.recent.addAction(action)
  5415. except KeyError:
  5416. App.log.error("Unsupported file type: %s" % recent["kind"])
  5417. # Last action in Recent Files menu is one that Clear the content
  5418. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5419. clear_action.triggered.connect(reset_recent)
  5420. self.ui.recent.addSeparator()
  5421. self.ui.recent.addAction(clear_action)
  5422. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5423. # self.ui.menufilerecent.set_submenu(recent_menu)
  5424. # recent_menu.show_all()
  5425. # self.ui.recent.show()
  5426. self.log.debug("Recent items list has been populated.")
  5427. def setup_component_editor(self):
  5428. # label = QtWidgets.QLabel("Choose an item from Project")
  5429. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5430. sel_title = QtWidgets.QTextEdit(
  5431. '<b>Shortcut Key List</b>')
  5432. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5433. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5434. # font = self.sel_title.font()
  5435. # font.setPointSize(12)
  5436. # self.sel_title.setFont(font)
  5437. selected_text = '''
  5438. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5439. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5440. The normal flow when working in FlatCAM is the following:</span></p>
  5441. <ol>
  5442. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5443. <br />
  5444. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5445. &nbsp;</li>
  5446. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5447. <br />
  5448. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5449. <br />
  5450. You can change the parameters in this screen and the flow direction is like this:<br />
  5451. <br />
  5452. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5453. </ol>
  5454. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5455. '''
  5456. sel_title.setText(selected_text)
  5457. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5458. self.ui.selected_scroll_area.setWidget(sel_title)
  5459. # tool_title = QtWidgets.QTextEdit(
  5460. # '<b>Shortcut Key List</b>')
  5461. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5462. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5463. # # font = self.sel_title.font()
  5464. # # font.setPointSize(12)
  5465. # # self.sel_title.setFont(font)
  5466. #
  5467. # tool_text = '''
  5468. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5469. #
  5470. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5471. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5472. #
  5473. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5474. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5475. #
  5476. # <ol>
  5477. # </ol>
  5478. #
  5479. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5480. #
  5481. # '''
  5482. #
  5483. # tool_title.setText(tool_text)
  5484. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5485. #
  5486. # self.ui.tool_scroll_area.setWidget(tool_title)
  5487. def setup_obj_classes(self):
  5488. """
  5489. Sets up application specifics on the FlatCAMObj class.
  5490. :return: None
  5491. """
  5492. FlatCAMObj.app = self
  5493. ObjectCollection.app = self
  5494. FCProcess.app = self
  5495. FCProcessContainer.app = self
  5496. def version_check(self):
  5497. """
  5498. Checks for the latest version of the program. Alerts the
  5499. user if theirs is outdated. This method is meant to be run
  5500. in a separate thread.
  5501. :return: None
  5502. """
  5503. self.log.debug("version_check()")
  5504. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5505. full_url = App.version_url + \
  5506. "?s=" + str(self.defaults['global_serial']) + \
  5507. "&v=" + str(self.version) + \
  5508. "&os=" + str(self.os) + \
  5509. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5510. else:
  5511. # no_stats dict; just so it won't break things on website
  5512. no_ststs_dict = {}
  5513. no_ststs_dict["global_ststs"] = {}
  5514. full_url = App.version_url + \
  5515. "?s=" + str(self.defaults['global_serial']) + \
  5516. "&v=" + str(self.version) + \
  5517. "&os=" + str(self.os) + \
  5518. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5519. App.log.debug("Checking for updates @ %s" % full_url)
  5520. ### Get the data
  5521. try:
  5522. f = urllib.request.urlopen(full_url)
  5523. except:
  5524. # App.log.warning("Failed checking for latest version. Could not connect.")
  5525. self.log.warning("Failed checking for latest version. Could not connect.")
  5526. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5527. return
  5528. try:
  5529. data = json.load(f)
  5530. except Exception as e:
  5531. App.log.error("Could not parse information about latest version.")
  5532. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5533. App.log.debug("json.load(): %s" % str(e))
  5534. f.close()
  5535. return
  5536. f.close()
  5537. ### Latest version?
  5538. if self.version >= data["version"]:
  5539. App.log.debug("FlatCAM is up to date!")
  5540. self.inform.emit("[success] FlatCAM is up to date!")
  5541. return
  5542. App.log.debug("Newer version available.")
  5543. self.message.emit(
  5544. "Newer Version Available",
  5545. str("There is a newer version of FlatCAM " +
  5546. "available for download:<br><br>" +
  5547. "<B>" + data["name"] + "</b><br>" +
  5548. data["message"].replace("\n", "<br>")),
  5549. "info"
  5550. )
  5551. def on_zoom_fit(self, event):
  5552. """
  5553. Callback for zoom-out request. This can be either from the corresponding
  5554. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5555. with axes limits from the geometry bounds of all objects.
  5556. :param event: Ignored.
  5557. :return: None
  5558. """
  5559. self.plotcanvas.fit_view()
  5560. def disable_all_plots(self):
  5561. self.report_usage("disable_all_plots()")
  5562. self.disable_plots(self.collection.get_list())
  5563. self.inform.emit("[success]All plots disabled.")
  5564. def disable_other_plots(self):
  5565. self.report_usage("disable_other_plots()")
  5566. self.disable_plots(self.collection.get_non_selected())
  5567. self.inform.emit("[success]All non selected plots disabled.")
  5568. def enable_all_plots(self):
  5569. self.report_usage("enable_all_plots()")
  5570. self.enable_plots(self.collection.get_list())
  5571. self.inform.emit("[success]All plots enabled.")
  5572. # TODO: FIX THIS
  5573. '''
  5574. By default this is not threaded
  5575. If threaded the app give warnings like this:
  5576. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5577. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5578. '''
  5579. def enable_plots(self, objects, threaded=False):
  5580. if threaded is True:
  5581. def worker_task(app_obj):
  5582. percentage = 0.1
  5583. try:
  5584. delta = 0.9 / len(objects)
  5585. except ZeroDivisionError:
  5586. self.progress.emit(0)
  5587. return
  5588. for obj in objects:
  5589. obj.options['plot'] = True
  5590. percentage += delta
  5591. self.progress.emit(int(percentage*100))
  5592. self.progress.emit(0)
  5593. self.plots_updated.emit()
  5594. self.collection.update_view()
  5595. # Send to worker
  5596. # self.worker.add_task(worker_task, [self])
  5597. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5598. else:
  5599. for obj in objects:
  5600. obj.options['plot'] = True
  5601. self.progress.emit(0)
  5602. self.plots_updated.emit()
  5603. self.collection.update_view()
  5604. # TODO: FIX THIS
  5605. '''
  5606. By default this is not threaded
  5607. If threaded the app give warnings like this:
  5608. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5609. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5610. '''
  5611. def disable_plots(self, objects, threaded=False):
  5612. # TODO: This method is very similar to replot_all. Try to merge.
  5613. """
  5614. Disables plots
  5615. :param objects: list
  5616. Objects to be disabled
  5617. :return:
  5618. """
  5619. if threaded is True:
  5620. self.progress.emit(10)
  5621. def worker_task(app_obj):
  5622. percentage = 0.1
  5623. try:
  5624. delta = 0.9 / len(objects)
  5625. except ZeroDivisionError:
  5626. self.progress.emit(0)
  5627. return
  5628. for obj in objects:
  5629. obj.options['plot'] = False
  5630. percentage += delta
  5631. self.progress.emit(int(percentage*100))
  5632. self.progress.emit(0)
  5633. self.plots_updated.emit()
  5634. self.collection.update_view()
  5635. # Send to worker
  5636. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5637. else:
  5638. for obj in objects:
  5639. obj.options['plot'] = False
  5640. self.plots_updated.emit()
  5641. self.collection.update_view()
  5642. def clear_plots(self):
  5643. objects = self.collection.get_list()
  5644. for obj in objects:
  5645. obj.clear(obj == objects[-1])
  5646. # Clear pool to free memory
  5647. self.clear_pool()
  5648. def generate_cnc_job(self, objects):
  5649. self.report_usage("generate_cnc_job()")
  5650. # for obj in objects:
  5651. # obj.generatecncjob()
  5652. for obj in objects:
  5653. obj.on_generatecnc_button_click()
  5654. def save_project(self, filename):
  5655. """
  5656. Saves the current project to the specified file.
  5657. :param filename: Name of the file in which to save.
  5658. :type filename: str
  5659. :return: None
  5660. """
  5661. self.log.debug("save_project()")
  5662. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5663. ## Capture the latest changes
  5664. # Current object
  5665. try:
  5666. self.collection.get_active().read_form()
  5667. except:
  5668. self.log.debug("[WARNING] There was no active object")
  5669. pass
  5670. # Project options
  5671. self.options_read_form()
  5672. # Serialize the whole project
  5673. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5674. "options": self.options,
  5675. "version": self.version}
  5676. # Open file
  5677. try:
  5678. f = open(filename, 'w')
  5679. except IOError:
  5680. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5681. return
  5682. # Write
  5683. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5684. f.close()
  5685. # verification of the saved project
  5686. # Open and parse
  5687. try:
  5688. saved_f = open(filename, 'r')
  5689. except IOError:
  5690. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5691. return
  5692. try:
  5693. saved_d = json.load(saved_f, object_hook=dict2obj)
  5694. except:
  5695. self.inform.emit("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5696. f.close()
  5697. return
  5698. saved_f.close()
  5699. if 'version' in saved_d:
  5700. self.inform.emit("[success] Project saved to: %s" % filename)
  5701. else:
  5702. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5703. def on_options_app2project(self):
  5704. """
  5705. Callback for Options->Transfer Options->App=>Project. Copies options
  5706. from application defaults to project defaults.
  5707. :return: None
  5708. """
  5709. self.report_usage("on_options_app2project")
  5710. self.defaults_read_form()
  5711. self.options.update(self.defaults)
  5712. self.options_write_form()
  5713. def on_options_project2app(self):
  5714. """
  5715. Callback for Options->Transfer Options->Project=>App. Copies options
  5716. from project defaults to application defaults.
  5717. :return: None
  5718. """
  5719. self.report_usage("on_options_project2app")
  5720. self.options_read_form()
  5721. self.defaults.update(self.options)
  5722. self.defaults_write_form()
  5723. def on_options_project2object(self):
  5724. """
  5725. Callback for Options->Transfer Options->Project=>Object. Copies options
  5726. from project defaults to the currently selected object.
  5727. :return: None
  5728. """
  5729. self.report_usage("on_options_project2object")
  5730. self.options_read_form()
  5731. obj = self.collection.get_active()
  5732. if obj is None:
  5733. self.inform.emit("WARNING: No object selected.")
  5734. return
  5735. for option in self.options:
  5736. if option.find(obj.kind + "_") == 0:
  5737. oname = option[len(obj.kind) + 1:]
  5738. obj.options[oname] = self.options[option]
  5739. obj.to_form() # Update UI
  5740. def on_options_object2project(self):
  5741. """
  5742. Callback for Options->Transfer Options->Object=>Project. Copies options
  5743. from the currently selected object to project defaults.
  5744. :return: None
  5745. """
  5746. self.report_usage("on_options_object2project")
  5747. obj = self.collection.get_active()
  5748. if obj is None:
  5749. self.inform.emit("WARNING: No object selected.")
  5750. return
  5751. obj.read_form()
  5752. for option in obj.options:
  5753. if option in ['name']: # TODO: Handle this better...
  5754. continue
  5755. self.options[obj.kind + "_" + option] = obj.options[option]
  5756. self.options_write_form()
  5757. def on_options_object2app(self):
  5758. """
  5759. Callback for Options->Transfer Options->Object=>App. Copies options
  5760. from the currently selected object to application defaults.
  5761. :return: None
  5762. """
  5763. self.report_usage("on_options_object2app")
  5764. obj = self.collection.get_active()
  5765. if obj is None:
  5766. self.inform.emit("WARNING: No object selected.")
  5767. return
  5768. obj.read_form()
  5769. for option in obj.options:
  5770. if option in ['name']: # TODO: Handle this better...
  5771. continue
  5772. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5773. self.defaults_write_form()
  5774. def on_options_app2object(self):
  5775. """
  5776. Callback for Options->Transfer Options->App=>Object. Copies options
  5777. from application defaults to the currently selected object.
  5778. :return: None
  5779. """
  5780. self.report_usage("on_options_app2object")
  5781. self.defaults_read_form()
  5782. obj = self.collection.get_active()
  5783. if obj is None:
  5784. self.inform.emit("WARNING: No object selected.")
  5785. return
  5786. for option in self.defaults:
  5787. if option.find(obj.kind + "_") == 0:
  5788. oname = option[len(obj.kind) + 1:]
  5789. obj.options[oname] = self.defaults[option]
  5790. obj.to_form() # Update UI
  5791. # end of file